How to decode unicode raw literals to readable string?

白昼怎懂夜的黑 提交于 2019-12-18 11:18:55

问题


If I assign unicode raw literals to a variable, I can read its value:

>>> s =  u'\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e'
>>> s
u'\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e'
>>> print s
Сообщение отправлено

But when I have already assigned value to a plain, not unicode string, I can not:

>>> s =  '\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e'
>>> s
'\\u0421\\u043e\\u043e\\u0431\\u0449\\u0435\\u043d\\u0438\\u0435 \\u043e\\u0442\\u043f\\u0440\\u0430\\u0432\\u043b\\u0435\\u043d\\u043e'
>>> print s
\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e

How can I decode and read it?


回答1:


Use the unicode_escape codec:

s.decode('unicode_escape')



回答2:


If you are getting weird results when decoding try following

print repr(s).decode('unicode-escape').encode('latin-1') // or encode using some other encoding

It could be that python terminal is using default ASCII and there is symbol that goes out of range.



来源:https://stackoverflow.com/questions/6504200/how-to-decode-unicode-raw-literals-to-readable-string

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