简体   繁体   English

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

[英]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.

相关问题 Python将字符串转换为元组 - Python converts string into tuple 元组中正确索引的代码。 Python - Code for correct indexation in tuple. Python 如何从txt文件中获取数据并将其输入到元组。 蟒蛇 - How to take data from a txt file and input it into a tuple. Python 类型错误:必须是 pygame.Surface,而不是元组。 Python/Pygame 菜鸟 - TypeError: must be pygame.Surface, not tuple. Python/Pygame noobie 元组的元组只有一个元组时,无法解包元组。 为什么? 与元组数组一起使用 - Can't unpack tuples when tuple of tuples has single tuple. Why? Works with array of tuples 编辑一个元组。 并访问元组的索引 - Editing A tuple. and accessing the index of tuple Django RelatedManager将元组转换为Unicode字符串吗? - Django RelatedManager converts tuple to Unicode string? Python正则表达式错误与元组。 使用列表。 错误的转义(模式结束) - Python regex error with tuple. Works with list. Bad escape (end of pattern) Python 类型错误:列表索引必须是整数或切片,而不是元组。 凯撒 Cypher 解码器 - Python TypeError: list indices must be integers or slices, not tuple. Caesar Cypher Decoder 细绳 ”????” 转换为 Python 中的“数据” - String "????" converts to "data" in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM