Need help with tuples in python
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 ou开发者_运维知识库tput (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?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.
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
(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.
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
精彩评论