[英]Python string converts magically to tuple. Why?
I've got a dict in which I load some info, among others a name which is a plain string. 我有一个dict,其中我加载了一些信息,其中一个名称是一个普通的字符串。 But somehow, when I assign it to a key in the dict it gets converted to a tuple, and I have no idea why.
但不知何故,当我将它分配给dict中的一个键时,它会转换为一个元组,我不知道为什么。
Here's some of my code: 这是我的一些代码:
sentTo = str(sentTo)
print type(sentTo), sentTo
ticketJson['sentTo'] = sentTo,
print type(ticketJson['sentTo']), ticketJson['sentTo']
which outputs the following on my terminal: 在我的终端输出以下内容:
<type 'str'> Pete Chasin
<type 'tuple'> ('Pete Chasin',)
Why does assigning it to a dict convert it to a tuple? 为什么将它分配给dict会将其转换为元组?
You told Python to create a tuple containing a string: 你告诉Python创建一个包含字符串的元组:
ticketJson['sentTo'] = sentTo,
# ^
It is the comma that defines a tuple. 它是定义元组的逗号。 Parentheses are only needed to disambiguate a tuple from other uses of a comma, such as in a function call.
只需要括号来消除元组与逗号的其他用法的歧义,例如在函数调用中。
From the Parenthesized forms section : 从括号表单部分 :
Note that tuples are not formed by the parentheses, but rather by use of the comma operator.
请注意,元组不是由括号组成,而是使用逗号运算符。 The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.
唯一的例外是空的元组,为此括号是必需的-允许在表达式中括号的“一无所有”会引起歧义,并允许普通错别字通过未捕获。
and from Expression lists : 从表达式列表 :
An expression list containing at least one comma yields a tuple.
包含至少一个逗号的表达式列表产生一个元组。 The length of the tuple is the number of expressions in the list.
元组的长度是列表中表达式的数量。 The expressions are evaluated from left to right.
表达式从左到右进行评估。
ticketJson['sentTo'] = sentTo,
是单元素元组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.