python str 和 tuple 对象的区别 [英] Distinction between python str and tuple objects

查看:70
本文介绍了python str 和 tuple 对象的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 如何初始化元组对象?例如,当我创建像

这样的对象时<预><代码>>>>对象 = ('鲨鱼')

显示对象类型为str

<预><代码>>>>类型(对象)<输入'str'>

虽然,如果我创建一个对象

<预><代码>>>>对象 = ('鲨鱼',)

它将其类型显示为 tuple

<预><代码>>>>类型(对象)<输入元组">

为什么会这样??python 究竟是如何创建/初始化一个元组、str 对象的?

解决方案

来自 文档:

<块引用>

一个特殊的问题是构造包含 0 或 1 的元组项目:语法有一些额外的怪癖来适应这些.空的元组由一对空括号构成;一个元组一个项目是通过一个带逗号的值来构造的(它不是足以将单个值括在括号中).

所以,如果没有尾随 , 这两个语句是等价的:

<预><代码>>>>x = 1>>>X1>>>x = (1)>>>X1

但这些都是元组:

<预><代码>>>>x = 1, #or (1,)>>>X(1,)>>>x = 1, 2, 3 #或 (1, 2, 3)>>>X(1, 2, 3)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆