gpt4 book ai didi

python - 在 python 2.7 中将字符串编码为 un​​icode 时出错?

转载 作者:行者123 更新时间:2023-12-01 05:07:46 25 4
gpt4 key购买 nike

我想在 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)

编辑:我尝试了以下方法:

>>> 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!'
>>>

最佳答案

在 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+ 兼容的代码。

关于python - 在 python 2.7 中将字符串编码为 un​​icode 时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24742886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com