__str __()调用场景后面的decode()方法吗?

Mer*_*glu 0 python string django unicode

在我看来,内置函数__repr____str__它们的基本定义有重要区别.

>>> t2 = u'\u0131\u015f\u0131k'
>>> print t2
???k
>>> t2
Out[0]: u'\u0131\u015f\u0131k'
Run Code Online (Sandbox Code Playgroud)

t2.decode因为t2是unicode字符串而引发错误.

>>> enc = 'utf-8'
>>> t2.decode(enc)
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
  File "C:\java\python\Python25\Lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin
al not in range(128)
Run Code Online (Sandbox Code Playgroud)

__str__引发错误,就像decode()调用函数一样:

>>> t2.__str__()
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordin
al not in range(128)
Run Code Online (Sandbox Code Playgroud)

__repr__没有问题:

>>> t2.__repr__()
Out[0]: "u'\\u0131\\u015f\\u0131k'"
Run Code Online (Sandbox Code Playgroud)

为什么会__str__产生错误而__repr__工作正常?

这个小差异似乎导致我正在处理的一个django应用程序中的错误.

Mic*_*ley 7

基本上,__str__只能输出ascii字符串.由于t2包含ascii以上的unicode代码点,因此无法仅使用字符串表示.__repr__另一方面,尝试输出重新创建对象所需的python代码.您将看到repr(t2)的输出(此语法首选t2.__repr_())正是您在第一行上将t2设置为等于up.repr的结果大致类似于['\','u','0',...],这些都是ascii值,但str的输出试图为[chr(0x0131),chr(0x015f) ,chr(0x0131),'k'],其中大部分都在python字符串中可接受的字符范围之上.通常,在处理django应用程序时,您应该使用__unicode__所有内容,而不要触摸__str__.

有关字符串的django文档更多信息.


Joh*_*kin 5

一般来说,调用str.__unicode__()或者unicode.__str__()是一个非常糟糕的主意,因为字节不能安全地转换为Unicode字符点,反之亦然.例外是ASCII值,在所有单字节编码中通常是相同的.问题是您使用了错误的转换方法.

要转换unicodestr,您应该使用encode():

>>> t1 = u"\u0131\u015f\u0131k"
>>> t1.encode("utf-8")
'\xc4\xb1\xc5\x9f\xc4\xb1k'
Run Code Online (Sandbox Code Playgroud)

要转换strunicode,请使用decode():

>>> t2 = '\xc4\xb1\xc5\x9f\xc4\xb1k'
>>> t2.decode("utf-8")
u'\u0131\u015f\u0131k'
Run Code Online (Sandbox Code Playgroud)