这种行为是意料之中的:您传递给底部两个示例中的函数的元组代表可变参数 *args 元组中的第一个参数(名称无关紧要,您使用的是 *n)。 *args 的目的是创建一个元组,其中包含传递给函数的所有非关键字参数。
创建单个元素的元组总是打印尾随逗号以将其区分为元组。在下面两种情况下,您有一个单元素 args 元组,其中一个 4 或 2 个元素的元组作为其唯一元素。
您的句子“将字符串添加到参数时,元组后出现逗号”不正确-您从调用中删除了解包运算符*,该调用不再将元组扁平化为可变参数,因此字符串无关用它。即使您将数字作为唯一参数传递,您仍然会得到悬挂的逗号:
>>> def f(*args): print(args)
...
>>> f(1)
(1,) # `args` tuple contains one number
>>> f(1, 2)
(1, 2) # `args` tuple contains two numbers
>>> f((1, 2))
((1, 2),) # two-element tuple `(1, 2)` inside single-element `args` tuple
>>> f((1,))
((1,),) # single-element tuple `(1,)` inside single-element `args` tuple
>>> f(*(1,)) # unpack the tuple in the caller, same as `f(1)`
(1,)
>>> f(*(1,2)) # as above but with 2 elements
(1, 2)
>>> f((1)) # without the trailing comma, `(1)` resolves to `1` and is not a tuple
(1,)