Python 字符串神奇地转换为元组。为什么?

Python string converts magically to tuple. Why?

我有一个字典,我在其中加载了一些信息,其中包括一个纯字符串名称。但是不知何故,当我将它分配给字典中的一个键时,它被转换为一个元组,我不知道为什么。

这是我的一些代码:

sentTo = str(sentTo)
print type(sentTo), sentTo
ticketJson['sentTo'] = sentTo,
print type(ticketJson['sentTo']), ticketJson['sentTo']

在我的终端上输出以下内容:

<type 'str'> Pete Chasin
<type 'tuple'> ('Pete Chasin',)

为什么将其分配给字典会将其转换为元组?

您告诉 Python 创建一个包含字符串的元组:

ticketJson['sentTo'] = sentTo,
#                            ^

定义元组的是逗号。括号仅用于消除元组与逗号的其他用途的歧义,例如在函数调用中。

来自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.

来自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, 是单元素元组