【问题标题】:Printing Unicode Char inside a List在列表中打印 Unicode 字符
【发布时间】:2014-01-23 16:36:30
【问题描述】:
a = ['M\xc3\xa3e']
b = 'M\xc3\xa3e'
print a
print b

结果:

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

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

【问题讨论】:

  • 通常你想打印单个元素,而不是它们的表示。
  • @Matthias,如果是这种情况, print 'b' 将需要打印 'M\xc3\xa3e'。
  • @f.rodriguez:嗯,这就是str 和repr 之间的区别。当您打印列表时,repr 用于每个元素。

标签: python python-2.7 unicode


【解决方案1】:

在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]

【讨论】:

    【解决方案2】:

    这是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) + ']'
    

    【讨论】:

      【解决方案3】:

      供个人使用,这个模块https://github.com/moskytw/uniout会非常方便。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-22
        • 2013-05-23
        • 2013-02-03
        相关资源
        最近更新 更多