如何将ASCII字符串视为unicode并在python中对其中的转义字符进行转换?

Joh*_*ohn 26 python unicode ascii

例如,如果我有一个unicode字符串,我可以将其编码为ASCII字符串,如下所示:

>>> u'\u003cfoo/\u003e'.encode('ascii')
'<foo/>'
Run Code Online (Sandbox Code Playgroud)

但是,我有这个ASCII字符串:

'\u003foo\u003e'
Run Code Online (Sandbox Code Playgroud)

...我想变成与上面第一个例子中相同的ASCII字符串:

'<foo/>'
Run Code Online (Sandbox Code Playgroud)

har*_*ark 47

我花了一段时间才想出这个,但这个页面有最好的答案:

>>> s = '\u003cfoo/\u003e'
>>> s.decode( 'unicode-escape' )
u'<foo/>'
>>> s.decode( 'unicode-escape' ).encode( 'ascii' )
'<foo/>'
Run Code Online (Sandbox Code Playgroud)

还有一个'raw-unicode-escape'编解码器来处理指定Unicode字符串的另一种方式 - 检查链接页面的"Unicode Constructors"部分以获取更多细节(因为我不是那种Unicode-saavy).

编辑:另请参阅Python标准编码.