如何使Python字符串版本无关

Cer*_*rin 1 python string unicode python-2.7 python-3.x

你如何使Python字符串与他们使用的Python版本无关?

我正在尝试维护适用于Python 2.7和Python 3*的代码,并且我遇到了许多反直觉错误.例如,这在Python 2.7中完美运行:

print('Job: %s' % job)
Run Code Online (Sandbox Code Playgroud)

但它在Python 3.3中失败并出现错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 27: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

如果我将该行更改为:

print(('Job: %s' % job).encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

修复它在Python 3.3 ...但它打破了Python 2.7,现在抛出完全相同的错误.

尝试在Python中管理字符串感觉就像玩傻瓜一样.你如何可靠地编码字符串,以便它们适用于所有版本的Python?

wim*_*wim 5

这应该适用于Python 2.7和3.3+:

print(u'Job: {}'.format(job))
Run Code Online (Sandbox Code Playgroud)

如果它仍然失败,那么你的问题存在于其他地方.不知何故job已经编码,你需要正确定义__str____unicode__魔法.