python str 和 tuple 对象的区别 [英] Distinction between python str and tuple objects
问题描述
python 如何初始化元组对象?例如,当我创建像
这样的对象时<预><代码>>>>对象 = ('鲨鱼')显示对象类型为str
虽然,如果我创建一个对象
<预><代码>>>>对象 = ('鲨鱼',)它将其类型显示为 tuple
为什么会这样??python 究竟是如何创建/初始化一个元组、str 对象的?
来自 文档:
<块引用>一个特殊的问题是构造包含 0 或 1 的元组项目:语法有一些额外的怪癖来适应这些.空的元组由一对空括号构成;一个元组一个项目是通过一个带逗号的值来构造的(它不是足以将单个值括在括号中).
所以,如果没有尾随 ,
这两个语句是等价的:
但这些都是元组
:
How python initializes a tuple object ? For example, when I create an object like
>>> object = ('Shark')
It shows type of object as str
>>> type(object)
<type 'str'>
While, if I create an object like
>>> object = ('Shark',)
It displays its type as a tuple
>>> type(object)
<type 'tuple'>
Why so ?? How exactly python creates/initializes a tuple, str objects ?
From docs:
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).
So, without a trailing ,
these two statements are equivalent:
>>> x = 1
>>> x
1
>>> x = (1)
>>> x
1
But these are all tuples
:
>>> x = 1, #or (1,)
>>> x
(1,)
>>> x = 1, 2, 3 #or (1, 2, 3)
>>> x
(1, 2, 3)
这篇关于python str 和 tuple 对象的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!