为什么在函数中使用字符串解包后输出中出现逗号?

Why does a comma appear in the output after the string is used in unpacking in a function?

def func(*n):
    print(n)

func(1,2,3,4)
func(*(1,2,3))
func((1,2,3,'hey'))
func(('hey',1))
output:
(1, 2, 3, 4)
(1, 2, 3)
((1, 2, 3, 'hey'),)
(('hey', 1),)

当将字符串添加到参数时,逗号出现在元组之后。

您在后面看到 , 的原因是因为 () 是一个函数调用,其中 (some_object,) 是一个元组。

>>> tuple()
()
>>> tuple([None])
(None,)

当您为最后两个函数调用传递参数时,请注意双 (())

func((1,2,3,'hey'))
func(('hey',1))

所以你传递的是最后两个的元组。查看每个的类型

>>> type(('test'))
<class 'str'>
>>> type(('test', 1))
<class 'tuple'>

如果您不想要结尾的逗号,请删除 args

周围多余的 ()

此行为是预期的:您传递给底部两个示例中的函数的元组代表可变 *args 元组中的第一个参数(名称无关紧要,您使用 *n). *args 的目的是创建一个元组,其中包含传递给函数的所有非关键字参数。

创建单元素元组总是打印尾随逗号以将其区分为元组。在后两种情况下,您有一个单元素 args 元组,其中一个 4 或 2 元素元组作为其独立元素。

你的句子 "comma appears after tuple when string is added to the argument" 不正确——你从调用中删除了解包运算符 *,它不再将元组扁平化为变量参数,因此字符串与它无关。即使您将数字作为唯一参数传递,您仍然会得到悬挂的逗号:

>>> 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,)