考慮這個功能:儘管我正在執行str.decode(),但Python仍會拋出UnicodeEncodeError。爲什麼?
def escape(text):
print repr(text)
escaped_chars = []
for c in text:
try:
c = c.decode('ascii')
except UnicodeDecodeError:
c = '&{};'.format(htmlentitydefs.codepoint2name[ord(c)])
escaped_chars.append(c)
return ''.join(escaped_chars)
應該由相應的htmlentitydefs逃避所有非ASCII字符。不幸的是蟒蛇拋出
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 0: ordinal not in range(128)
當變量text
包含其repr()
是u'Tam\xe1s Horv\xe1th'
的字符串。我不使用str.encode()
。我只使用str.decode()
。我想念什麼?
你的意思是我應該抓住UnicodeEncodeError,也解決方案? – Aufwind 2011-12-21 14:10:14
或者是我逃避人物廢話的方法? – Aufwind 2011-12-21 14:13:23