给定从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后,一切正常:
^{pr2}$在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)
>>>
Python2.6.1和2.6.5之间是否发生了一些变化,需要对unicode字符串进行不同的处理?或者这和我(默认的Ubuntu服务器10.04lts)linux环境中配置错误有关吗?在
编辑:两个环境都有LANG=en_美国UTF-八
在C语言环境中也可能发生这种情况。尝试使用
LANG=en_US.UTF-8 python
运行Python,然后重试代码。在你试过给你的字符串加上u前缀吗?在
见http://docs.python.org/howto/unicode.html#unicode-literals-in-python-source-code
我可以使用以下命令重现错误:
^{pr2}$^{} 是
'ascii'
,默认情况下不太有用。在尝试使用控制台编码:
或者
检查
sys.stdout.encoding
:如果} 或设置{a3},如上图所示。见http://wiki.python.org/moin/PrintFails
sys.stdout.encoding
是None
,请尝试使用^{如果错误只发生在交互式Python会话中,请查看^{} 。在
相关问题 更多 >
编程相关推荐