Python-unicode在OSX上的2.6.1中可以工作,但在Ubuntu上不能在2.6.5中使用

2024-05-19 12:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

给定从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-八


Tags: inimportstring环境ubuntumysysascii
3条回答

在C语言环境中也可能发生这种情况。尝试使用LANG=en_US.UTF-8 python运行Python,然后重试代码。在

你试过给你的字符串加上u前缀吗?在

my_string = u'\xc3\xa9'

http://docs.python.org/howto/unicode.html#unicode-literals-in-python-source-code

In Python source code, Unicode literals are written as strings prefixed with the ‘u’ or ‘U’ character: u'abcdefghijk'. Specific code points can be written using the \u escape sequence, which is followed by four hex digits giving the code point. The \U escape sequence is similar, but expects 8 hex digits, not 4.

我可以使用以下命令重现错误:

$ PYTHONIOENCODING=ascii python -c'print "\xc3\xa9".decode("utf-8")'
^{pr2}$

^{}'ascii',默认情况下不太有用。在

尝试使用控制台编码:

$ PYTHONIOENCODING=utf-8 python -c'print "\xc3\xa9".decode("utf-8")'
é

或者

$ python -c'import locale; print "\xc3\xa9".decode("utf-8").encode(
> locale.getpreferredencoding())'
é

检查sys.stdout.encoding

$ python -c'import sys; o = sys.stdout; print o.isatty(), o.encoding'
True UTF-8

$ python -c'import sys; o = sys.stdout; print o.isatty(), o.encoding' | cat
False None

$ python -c'import sys; o = sys.stdout; print o.isatty(), o.encoding' >/tmp/out
$ cat /tmp/out
False None

如果sys.stdout.encodingNone,请尝试使用^{}或设置{a3},如上图所示。见http://wiki.python.org/moin/PrintFails

如果错误只发生在交互式Python会话中,请查看^{}。在

相关问题 更多 >