如何使Python字符串与他们正在使用的Python版本无关?
我试图维护适用于Python 2.7和Python 3 *的代码,并且我遇到了许多反直觉错误。例如,这在Python 2.7中非常有效:
print('Job: %s' % job)
但它在Python 3.3中失败并出现错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 27: ordinal not in range(128)
如果我将该行更改为:
print(('Job: %s' % job).encode('utf-8'))
修复了它在Python 3.3 ...但它破坏了Python 2.7,现在抛出完全相同的错误。
尝试在Python中管理字符串感觉就像玩傻瓜一样。你如何可靠地编码字符串,以便它们适用于所有版本的Python?
答案 0 :(得分:5)
这应该适用于Python 2.7和3.3+:
print(u'Job: {}'.format(job))
如果仍然失败,那么您的问题就存在于其他地方。某种程度上job
已被编码,您需要正确定义__str__
和__unicode__
魔法。
答案 1 :(得分:0)
six
库是为这样的东西构建的:
import six
print("%s" % six.u(job))
答案 2 :(得分:0)
解决方案将取决于您要定位的精确Python版本,但如果2.7足以实现向后兼容性,则可以添加
from __future__ import unicode_literals
这是Python 3中的无操作(至少3.2+)并且在Python 2.7中实现了您的期望。
bash$ python
Python 2.7.11 (default, Dec 26 2015, 17:47:15)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> type('hello')
<type 'unicode'>
>>> repr('Götterdämmerung')
"u'G\\xf6tterd\\xe4mmerung'"
请参阅http://python-future.org/unicode_literals.html处的警告,其中指出“未来”并未涵盖3.0-3.2。因此,这个特殊的东西似乎也像我在3.1中所期望的那样工作。