给定从Python解释器运行的以下代码:
import sys
sys.getdefaultencoding()
my_string = '\xc3\xa9'
my_string = unicode(my_string, 'utf-8')
my_string
print my_string在mac上运行Python 2.6.1时,一切都很正常:
$ python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> my_string = '\xc3\xa9'
>>> my_string = unicode(my_string, 'utf-8')
>>> my_string
u'\xe9'
>>> print my_string
é
>>> 在Ubuntu 10.04 LTS上运行Python 2.6.5时,它会失败:
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
>>> my_string = '\xc3\xa9'
>>> my_string = unicode(my_string, 'utf-8')
>>> my_string
u'\xe9'
>>> print my_string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
>>> Python 2.6.1和2.6.5之间是否有需要对unicode字符串进行不同处理的更改?或者这与我(默认的Ubuntu服务器10.04 LTS) linux环境中的某些配置错误有关?
编辑:两个环境都有LANG=en_US.UTF-8
发布于 2011-01-29 10:12:24
这可以发生在C语言环境中。尝试使用LANG=en_US.UTF-8 python运行Python,然后再次尝试您的代码。
发布于 2011-01-29 10:57:25
你有没有试过给字符串加上前缀u?
my_string = u'\xc3\xa9‘
请参阅http://docs.python.org/howto/unicode.html#unicode-literals-in-python-source-code
在Python源代码中,Unicode文本被写成带有‘u’或‘u’前缀的字符串:u‘’abcdefghijk‘。可以使用\u转义序列来编写特定的代码点,转义序列后跟四个十六进制数字,提供代码点。\U转义序列类似,但需要8位十六进制数字,而不是4位。
发布于 2020-01-13 22:00:51
正如@jfs回答的那样,
$ PYTHONIOENCODING=utf-8 python file.py 对我很管用。如果你想让它成为默认设置,你可以在你的basrc或zshrc中添加以下命令
export PYTHONIOENCODING="utf-8"https://stackoverflow.com/questions/4834661
复制相似问题