エンコーディングエラーの非常に一般的な原因は、Python 2で文字列をunicode
追加すると、文字列を強制的に強制変換することです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'
実際のエラーが実際の強制が発生した場所から遠く離れた場所にある場合、追跡するのは特に困難です。
文字列がUnicodeに強制変換されたときにすぐに警告または例外を出すようにPythonを構成するにはどうすればよいですか?