【问题标题】:Python Character Encoding Inconsistency Between Environments环境之间的 Python 字符编码不一致
【发布时间】:2014-03-05 02:26:30
【问题描述】:

服务器错误: 蟒蛇2.7

Traceback (most recent call last):
  File "promoter.py", line 325, in process_unfollowbacks
    self.add_user_to_database(user_info)
  File "promoter.py", line 618, in add_user_to_database
    str(u['name']),
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 11: ordinal not in range(128)

但是,它在 Ubuntu 上运行良好。

服务器:

Python 2.7.3 (default, Mar  2 2014, 10:09:03) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Ubuntu:

Python 2.7.5+ (default, Feb 27 2014, 19:37:08) 
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.

我在操作由 Twitter Json 数组(Twython 模块)产生的字典时遇到此错误,但我认为问题不存在。

稍加检查表明外语正在发生这种情况。

问题: 如何处理环境之间的这种不一致?

【问题讨论】:

    标签: python encoding character rhel


    【解决方案1】:

    “服务器”环境中的默认编码与 Ubuntu 环境不同。试试 u['name'].encode('utf-8')

    【讨论】:

    • .encode('utf-8') 是我做的第一件事,但即使这样也会引发错误。
    • 这会产生什么?打印 '%r' % u['name']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 2021-03-22
    • 2020-09-14
    相关资源
    最近更新 更多