【问题标题】:error encoding string as unicode in python 2.7?python 2.7中的错误编码字符串为unicode?
【发布时间】: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


【解决方案1】:

在 Python 2.x 中,您需要使用 unicode literal:

x=u"strings are now utf-8 \u03BCnico\u0394é!"

没有这个,encode 方法不知道字符串是什么编码,并假设它是 ASCII。然后它会尝试将 ASCII 转换为 UTF-8,并在遇到 ASCII 字符集之外的字符时失败。

另请注意,Python 3.3 及更高版本支持此表示法。在这种情况下,它基本上是无操作的,因为所有字符串都假定为 unicode,但允许开发人员编写与 2.x 和 3.3+ 兼容的代码。

【讨论】:

  • 我查看了您 OP 上的 cmets - 您还需要我查看您的更改吗?
猜你喜欢
  • 2012-03-23
  • 2011-08-11
  • 2013-10-29
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
相关资源
最近更新 更多