2014-01-06 115 views
3
a = ['M\xc3\xa3e'] 
b = 'M\xc3\xa3e' 
print a 
print b 

結果:打印Unicode字符列表裏面

['M\xc3\xa3e'] 
Mãe 

如何打印a,如:['Mãe']

+1

通常情況下,您想要打印各個元素,而不是它們的表示。 – Matthias

+1

另請參閱:http://stackoverflow.com/questions/16798811/print-list-of-unicode-chars-without-escape-characters – Yosh

+0

@Matthias,如果是這種情況,打印'B'需要打印'M \ xc3 \ xa3e'來代替。 –

回答

1

這是在python2

但在python3你會得到一個特點是什麼你要 :)。

$ python3 
Python 3.3.3 (default, Nov 26 2013, 13:33:18) 
[GCC 4.8.2] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> a = ['M\xc3\xa3e'] 
>>> print(a) 
['Mãe'] 
>>> 

或python2您可以:

print '[' + ','.join("'" + str(x) + "'" for x in a) + ']' 
2

在python2你也可以繼承list類,並使用__unicode__方法:

#Python 2.7.3 (default, Sep 26 2013, 16:38:10) 

>>> class mylist(list): 
... def __unicode__(self): 
... return '[%s]' % ', '.join(e.decode('utf-8') if isinstance(e, basestring) 
...        else str(e) for e in self) 
>>> a = mylist(['M\xc3\xa3e', 11]) 
>>> print a 
['M\xc3\xa3e', 11] 
>>> print unicode(a) 
[Mãe, 11]