Printing Unicode Char inside a List

2020-02-07 04:04发布

a = ['M\xc3\xa3e']
b = 'M\xc3\xa3e'
print a
print b

results:

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

How can I print a like: ['Mãe']

3条回答
时光不老,我们不散
2楼-- · 2020-02-07 05:01

In python2 you can subclass list class and use __unicode__ method:

#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]
查看更多
乱世女痞
3楼-- · 2020-02-07 05:02

For personal use, this module https://github.com/moskytw/uniout will come very handy.

查看更多
Evening l夕情丶
4楼-- · 2020-02-07 05:10

This is a feature in python2

But in python3 you will get what you want :).

$ 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']
>>> 

or in python2 you can:

print '[' + ','.join("'" + str(x) + "'" for x in a) + ']'
查看更多
登录 后发表回答