【发布时间】:2014-07-14 18:02:49
【问题描述】:
我想在 Python 2.7 中打印字符串的 unicode 版本。它在 Python 3 中运行良好。 但是使用 python 2.7,我收到以下错误:
x="strings are now utf-8 \u03BCnico\u0394é!"
Python 3:
print('Python', python_version())
print(x)
Python 3.4.1
strings are now utf-8 μnicoΔé!
Python 2.7
>>> x='strings are now utf-8 \u03BCnico\u0394é!'
>>> x.encode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 38: ordinal not in range(128)
编辑: 我试过followimg:
>>> x = u'strings are now utf-8 \\u03BCnico\\u0394\xc3\xa9!'
>>> x
u'strings are now utf-8 \\u03BCnico\\u0394\xc3\xa9!'
>>> x.encode("utf-8")
'strings are now utf-8 \\u03BCnico\\u0394\xc3\x83\xc2\xa9!'
>>> x
u'strings are now utf-8 \\u03BCnico\\u0394\xc3\xa9!'
我没有看到编码发生
编辑 2:
>>> x=u'strings are now utf-8 \u03BCnico\u0394é!'
>>> x.encode("utf-8")
'strings are now utf-8 \xce\xbcnico\xce\x94\xc3\xa9!'
>>> b=x.encode("utf-8")
>>> b
'strings are now utf-8 \xce\xbcnico\xce\x94\xc3\xa9!'
>>>
【问题讨论】:
-
您的第一个问题是您正在尝试对字节字符串进行编码。您将字节字符串解码为 unicode,然后将 unicode编码为特定编码的字节字符串(例如
utf-8)。 -
尝试打印不带
.encode()的unicode 文字print x。 -
您的第二个问题是您尝试在字节字符串中使用 unicode 转义序列 (
\u...) - 它们仅适用于 unicode 文字,如 @LyndsySimon 的回答所示。 -
另外:
str.encode()并没有像您在编辑部分中假设的那样正常运行。您需要查看encode()的结果以查看正在发生的编码,原始字符串不会改变。 -
@eagertoLearn 因为你不是
printing它 - 打印最后一个字符串,你会看到。如果您只是在解释器中输入一个变量,Python 会向您显示字符串的表示。
标签: python python-2.7 python-3.x unicode