Need help with tuples in python

旧巷老猫 提交于 2019-12-13 02:36:40

问题


When I print the tuple (u'1S²') I get the predicted output of 1S²

However, when I print the tuple (u'1S²',u'2S¹') I get the output (u'1S\xb2', u'2S\xb9').

Why is this? What can I do about this?
Also, how do I get the number of items in a tuple?


回答1:


The expression (u'1S²') is not a tuple, it's a unicode value. A 1-tuple is written in Python this way: (u'1S²',).

The print value statement prints a str(value) in fact. If you need to output several unicode strings, you should use something like this:

print u' '.join((u'1S²',u'2S¹'))

Though there might be issues with character encodings. If you know your console encoding, you may encode your unicode values to str manually:

ENCODING = 'utf-8'
print u' '.join((u'1S²',u'2S¹')).encode(ENCODING)

The number of iterms in tuples, lists, strings and other sequences can be obtained using len function.




回答2:


What platform and version of Python do you have? I don't see this behavior. I always get the \x escape sequences with Python 2.6:

Python 2.6.5 (r265:79063, Apr 26 2010, 10:14:53)
>>> (u'1S²')
u'1S\xb2'
>>> (u'1S²',)
(u'1S\xb2',)
>>> (u'1S²',u'1S¹')
(u'1S\xb2', u'1S\xb9')

As a side note, (u'1S²') isn't a tuple, it's just a string with parentheses around it. You need a comma afterwards to create a single element tuple: (u'1S²',).

As for the number of items, use len:

>>> len((u'1S²',u'1S¹'))
2



回答3:


(u'1S²') is not a tuple. (u'1S²',) is a tuple containing u'1S²'. len((u'1S²',)) returns the length of the tuple, that is, 1.

also, when printing variables, beware there are 2 types of output :

  • the programmer friendly string representation of the object : that is repr(the_object)
  • the text representation of the object, mostly applicable for strings

if the second is not availlable, the first is used. unlike strings, tuples don't have a text representation, hence the programmer friendly representation is used to represent the tuple and its content.




回答4:


Your first example (u'1S²') isn't actually a tuple, it's a unicode string!

>>> t = (u'1S²')
>>> type(t)
<type 'unicode'>
>>> print t
1S²

The comma is what makes it a tuple:

>>> t = (u'1S²',)
>>> type(t)
<type 'tuple'>
>>> print t
(u'1S\xb2',)

What's happening is when you print a tuple, you get the repr() of each of its components. To print the components, address them individually by index. You can get the length of a tuple with len():

>>> print t[0]
1S²
>>> len(t)
1


来源:https://stackoverflow.com/questions/3680245/need-help-with-tuples-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!