Python - How to convert utf literal such as '\xc3\xb6' to the letter ö

天大地大妈咪最大 提交于 2020-07-10 09:35:03

问题


I am trying to convert an encoded url with german Umlaute into a string with those Umlaute.

Here is an example of an encoded string = 'K%C3%B6nnen'. I would like to convert it to 'Können'

When I use urllib.unquote(a) I get this returned: 'K\xc3\xb6nnen'

\xc3\xb6 I found out is a utf literal.

How can I convert this to an ö ? I find that if I use the print function it converts it correctly, but I cannot figure out how to get a function to return this value? Any ideas?


回答1:


With decode("utf-8")

print('K\xc3\xb6nnen'.decode("utf-8"))

OUTPUT

Können

EXTRA edit, take care with that

>>> l = []
>>> l.append(s.decode("utf-8")) #s is the string
>>> l
[u'K\xf6nnen']
>>> print(l)
[u'K\xf6nnen']
>>> print(l[0])
Können
>>> 

Python will use codification to manage string, print can give you the representation but no the real value, use repr(s) for real value



来源:https://stackoverflow.com/questions/56081392/python-how-to-convert-utf-literal-such-as-xc3-xb6-to-the-letter-%c3%b6

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