如何将unicode原始文字解码为可读字符串



如果我将unicode原始文字分配给一个变量,我可以读取它的值:

>>> s =  u'u0421u043eu043eu0431u0449u0435u043du0438u0435 u043eu0442u043fu0440u0430u0432u043bu0435u043du043e'
>>> s
u'u0421u043eu043eu0431u0449u0435u043du0438u0435 u043eu0442u043fu0440u0430u0432u043bu0435u043du043e'
>>> print s
Сообщение отправлено

但是,当我已经为一个普通字符串(而不是unicode字符串)赋值时,我不能:

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

我如何解码和阅读它?

使用unicode_escape编解码器:

s.decode('unicode_escape')

如果解码时得到奇怪的结果,请尝试以下

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

可能是python终端使用默认的ASCII,并且有超出范围的符号。

最新更新