我在Python 3以下字符串:
bytestring = b'Zeer ge\xc3\xafnteresseerd naar iemands verhalen luisteren.'
我如何得到这与正常字符的字符串?那是:
'Zeer geïnteresseerd naar iemands verhalen luisteren.'
我已经尝试使用其解码:
bytestring.decode('utf-8)
但是,当我尝试打印值到控制台的Python给了我下面的错误:
UnicodeEncodeError: 'ascii' codec can't encode character '\xef' in position 7: ordinal not in range(128)
任何帮助表示赞赏。
解
我通过键入终端下面解决了这个问题:
export PYTHONIOENCODING=UTF-8
从那以后,我能够打印解码字节字符串到控制台。
好像你正在使用Unicode而不是字符串的工作。看看这有助于。您使用进行解码这个自定义功能;首先用UTF8,然后用Latin1的接着编码为ascii。
def CustomDecode(mystring):
'''Accepts string and tries decode with UTF8 first and then Latin1'''
c=''.join(map(lambda x: chr(ord(x)),mystring))
decval = None
try:
decval = c.decode('utf8')
except UnicodeDecodeError:
decval = c.decode('latin1')
return decval
CustomDecode(mystring).encode('ascii', 'ignore')
结果:
'Zeer genteresseerd naar iemands verhalen luisteren.'