gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:42:38 27 4
gpt4 key购买 nike

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'>

如果您不需要尾随逗号,请删除参数周围多余的 ()

关于python - 为什么在函数中使用字符串解包后,输出中会出现逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59377621/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com