Python 3.4 decode bytes

徘徊边缘 提交于 2019-12-08 18:44:59

问题


I am trying to write a file in python, and I can't find a way to decode a byte object before writing the file, basically, I am trying to decode this bytes string:

Les \xc3\x83\xc2\xa9vad\xc3\x83\xc2\xa9s

into this, which is the original text I'm trying to recover:

Les évadés

I tried using the .decode('utf-8') and encode('utf-8') but nothing seems to work...

I always get Les évadés as a result... I am using python 3.4.3

Anyone can help?


回答1:


And if you want a Python 3 solution:

b = b'Les \xc3\x83\xc2\xa9vad\xc3\x83\xc2\xa9s'
u = b.decode('utf-8').encode('latin-1').decode('utf-8')
print(u)
# Les évadés



回答2:


What you need to do is to decode and then encode:

s = "Les \xc3\x83\xc2\xa9vad\xc3\x83\xc2\xa9s"
utf = s.decode('utf-8')
latin = utf.encode("latin-1","ignore")
print latin

--> Les évadés



来源:https://stackoverflow.com/questions/30739936/python-3-4-decode-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!