为什么在变量名后添加尾随逗号使其成为元组? [英] Why does adding a trailing comma after a variable name make it a tuple?

查看:46
本文介绍了为什么在变量名后添加尾随逗号使其成为元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在变量名称(在本例中为字符串)后添加尾随逗号使其成为 tuple.即

<预><代码>>>>abc = 'mystring',>>>打印(ABC)('我的字符串',)

当我打印 abc 时,它返回 tuple ('mystring',).

解决方案

重要的是逗号,而不是括号.Python 教程说:

<块引用>

元组由多个以逗号分隔的值组成

括号用于在其他使用逗号的地方消除歧义,例如,使您能够嵌套或输入元组作为参数列表的一部分.

请参阅 关于元组和序列的 Python 教程部分

I want to know that why adding a trailing comma after a variable name (in this case a string) makes it a tuple. i.e.

>>> abc = 'mystring',
>>> print(abc)
('mystring',)

When I print abc it returns the tuple ('mystring',).

解决方案

It is the commas, not the parentheses, which are significant. The Python tutorial says:

A tuple consists of a number of values separated by commas

Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.

See the Python Tutorial section on Tuples and Sequences

这篇关于为什么在变量名后添加尾随逗号使其成为元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆