如果您需要Latin-1编码,则可以使用多种方法来消除破折号或其他255以上的代码点(Latin-1中不包含的字符):
>>> u = u'hello\u2013world'
>>> u.encode('latin-1', 'replace') # replace it with a question mark
'hello?world'
>>> u.encode('latin-1', 'ignore') # ignore it
'helloworld'
或自行定制替代品:
>>> u.replace(u'\u2013', '-').encode('latin-1')
'hello-world'
如果不需要输出Latin-1,则UTF-8是常见且首选的选择。W3C推荐它,并且很好地编码了所有Unicode代码点:
>>> u.encode('utf-8')
'hello\xe2\x80\x93world'