编码错误的一个常见来源是,当你将字符串和unicode字符串一起使用加号进行拼接时,Python 2会默默地将字符串强制转换为unicode
类型。这可能会导致混合编码问题,并且很难调试。
例如:
import urllib
import webbrowser
name = raw_input("What's your name?\nName: ")
greeting = "Hello, %s" % name
if name == "John":
greeting += u' (Feliz cumplea\xf1os!)'
webbrowser.open('http://lmgtf\x79.com?q=' + urllib.quote_plus(greeting))
如果输入“John”,它会因为一个神秘的错误而失败:
/usr/lib/python2.7/urllib.py:1268: UnicodeWarning: Unicode equal comparison faile
d to convert both arguments to Unicode - interpreting them as being unequal
return ''.join(map(quoter, s))
Traceback (most recent call last):
File "feliz.py", line 7, in <module>
webbrowser.open('http://lmgtf\x79.com?q=' + urllib.quote_plus(greeting))
File "/usr/lib/python2.7/urllib.py", line 1273, in quote_plus
s = quote(s, safe + ' ')
File "/usr/lib/python2.7/urllib.py", line 1268, in quote
return ''.join(map(quoter, s))
KeyError: u'\xf1'
当实际强制转换发生在很远的地方时,跟踪实际错误特别困难。
如何配置Python,在字符串被强制转换为Unicode时立即给出警告或异常?
unicode
字面量,需要时再进行编码呢? - Ignacio Vazquez-Abrams