V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
tabris17
V2EX  ›  Python

又是 py2 的 UnicodeEncodeError 问题

  •  
  •   tabris17 · 2015-05-14 19:19:23 +08:00 · 2154 次点击
    这是一个创建于 3296 天前的主题,其中的信息可能已经有所发展或是发生改变。
    现在问题出在第三方的库里,里面有类似 '{0}'.format(string) 的语句,而string是我传入的unicode。

    这么一来就UnicodeEncodeError了。

    现在的问题是如果在不修改第三方库源代码的情况下,使得代码可以支持中文。

    reload(sys) 什么的就算了
    4 条回复    2015-05-15 02:59:44 +08:00
    messense
        1
    messense  
       2015-05-14 19:23:53 +08:00   ❤️ 1
    In [1]: def func(s):
    ...: return '{0}'.format(s)
    ...:

    In [2]: func('123')
    Out[2]: '123'

    In [3]: func(u'呵呵')
    ---------------------------------------------------------------------------
    UnicodeEncodeError Traceback (most recent call last)
    <ipython-input-3-f4d18df38e04> in <module>()
    ----> 1 func(u'呵呵')

    <ipython-input-1-62fe9e7b06ab> in func(s)
    1 def func(s):
    ----> 2 return '{0}'.format(s)
    3

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

    In [4]: func(u'呵呵'.encode('utf-8'))
    Out[4]: '\xe5\x91\xb5\xe5\x91\xb5'
    gamexg
        2
    gamexg  
       2015-05-14 20:55:54 +08:00 via Android
    重写format?
    imn1
        3
    imn1  
       2015-05-14 21:43:54 +08:00
    In [5]: u'{0}'.format(u'中文')
    Out[5]: u'\u4e2d\u6587'
    Sylv
        4
    Sylv  
       2015-05-15 02:59:44 +08:00 via iPhone   ❤️ 1
    这是这个库没考虑到 Unicode 的情况。
    最根本的方法是修改库的源码,给前面加个 u,还可以给作者发个 PR。
    如果不想改人家源码的话,只好先将 string.encode('utf-8') 后再传入第三方的库方法。
    其实 Python 2 自带的库有些方法也不支持 Unicode。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2569 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 14:51 · PVG 22:51 · LAX 07:51 · JFK 10:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.