在Python中如何对Unicode转义字符串进行反转义?

10

我有一个 Unicode 转义字符串:

> str = 'blah\\x2Ddude'

我想将这个字符串转换为未转义的Unicode版本:'blah-dude'

我该怎么做?


这不是HTML转义字符串。尝试:import html; html.escape('this <is> &escaped&')html.unescape('this &lt;is&gt; &amp;escaped&amp;') - jfs
字符串从哪里来?你理解 '\\x2d''\x2d' 之间的区别吗? - jfs
1个回答

15

将其编码为bytes(使用任何编解码器,通常utf-8可以)然后使用unicode-escape进行解码:

s = 'blah\\x2Ddude'

s.encode().decode('unicode-escape')
Out[133]: 'blah-dude'

4
不需要调用 encode 函数。你只需要 import codecs 然后调用 codecs.decode(s, 'unicode-escape') 即可。 - Mark H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接