代码之家  ›  专栏  ›  技术社区  ›  user1267132

Python unicode错误

  •  1
  • user1267132  · 技术社区  · 11 年前

    有人能在下面的例子中解释一下为什么吗, print a 引发异常,而 a.__str__() 不?

    >>> class A:
    ...   def __init__(self):
    ...     self.t1 = "čakovec".decode("utf-8")
    ...     self.t2 = "tg"
    ...   def __str__(self):
    ...     return self.t1 + self.t2
    ... 
    >>> a = A()
    >>> print a
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character u'\u010d' in position 0: ordinal not in range(128)
    >>> a.__str__()
    u'\u010dakovectg'
    >>> print a.__str__()
    čakovectg
    
    1 回复  |  直到 11 年前
        1
  •  6
  •   Phillip Cloud    11 年前

    在Python 2中 str 必须返回ASCII字符串。当你打电话时 __str__ 直接跳过Python转换 __字符串__ 转换为ASCII字符串(事实上,您可以从 __字符串__ ,但你不应该)。 __字符串__ 不应返回 unicode 对象,它应该返回 字符串 对象

    以下是您可以做的事情:

    In [29]: class A(object):
        ...:     def __init__(self):
        ...:         self.t1 = u"c∃".encode('utf8')
        ...:     def __str__(self):
        ...:         return self.t1
        ...:     
    
    In [30]: a = A()
    
    In [31]: print a
    c∃
    
    In [32]: str(a)
    Out[32]: 'c\xe2\x88\x83'
    
    In [33]: a.__str__()
    Out[33]: 'c\xe2\x88\x83'