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

2024-07-03 07:13:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dict,在其中我加载了一些信息,其中一个名字是一个普通的字符串。但不知怎么的,当我把它赋给dict中的一个键时,它会被转换成一个元组,我不知道为什么。你知道吗

以下是我的一些代码:

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

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

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

为什么把它赋给dict会把它转换成元组呢?你知道吗


Tags: 字符串代码信息终端type名字dict元组
2条回答

您让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,是单元素元组

相关问题 更多 >