推荐学习书目
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 · May 14, 2015 · 2687 views
    This topic created in 4015 days ago, the information mentioned may be changed or developed.
    现在问题出在第三方的库里,里面有类似 '{0}'.format(string) 的语句,而string是我传入的unicode。

    这么一来就UnicodeEncodeError了。

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

    reload(sys) 什么的就算了
    4 replies    2015-05-15 02:59:44 +08:00
    messense
        1
    messense  
       May 14, 2015   ❤️ 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  
       May 14, 2015 via Android
    重写format?
    imn1
        3
    imn1  
       May 14, 2015
    In [5]: u'{0}'.format(u'中文')
    Out[5]: u'\u4e2d\u6587'
    Sylv
        4
    Sylv  
       May 15, 2015 via iPhone   ❤️ 1
    这是这个库没考虑到 Unicode 的情况。
    最根本的方法是修改库的源码,给前面加个 u,还可以给作者发个 PR。
    如果不想改人家源码的话,只好先将 string.encode('utf-8') 后再传入第三方的库方法。
    其实 Python 2 自带的库有些方法也不支持 Unicode。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3781 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 04:55 · PVG 12:55 · LAX 21:55 · JFK 00:55
    ♥ Do have faith in what you're doing.