首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python unicode可以在OSX的2.6.1版本中运行,但不能在Ubuntu的2.6.5版本中运行

Python unicode可以在OSX的2.6.1版本中运行,但不能在Ubuntu的2.6.5版本中运行
EN

Stack Overflow用户
提问于 2011-01-29 10:03:55
回答 3查看 1.4K关注 0票数 3

给定从Python解释器运行的以下代码:

代码语言:javascript
复制
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时,一切都很正常:

代码语言:javascript
复制
$ 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时,它会失败:

代码语言:javascript
复制
$ 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

EN

回答 3

Stack Overflow用户

发布于 2011-01-29 10:12:24

这可以发生在C语言环境中。尝试使用LANG=en_US.UTF-8 python运行Python,然后再次尝试您的代码。

票数 4
EN

Stack Overflow用户

发布于 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位。

票数 0
EN

Stack Overflow用户

发布于 2020-01-13 22:00:51

  • Python 3.6.8或newer

正如@jfs回答的那样,

代码语言:javascript
复制
$ PYTHONIOENCODING=utf-8 python file.py 

对我很管用。如果你想让它成为默认设置,你可以在你的basrczshrc中添加以下命令

代码语言:javascript
复制
export PYTHONIOENCODING="utf-8"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4834661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档