如何将ASCII字符串视为unicode,并在python中取消转义其中的转义字符? [英] How do I treat an ASCII string as unicode and unescape the escaped characters in it in python?
问题描述
例如,如果我有一个 unicode 字符串,则可以将其编码为 ASCII 字符串,如下所示:
For example, if I have a unicode string, I can encode it as an ASCII string like so:
>>> u'\u003cfoo/\u003e'.encode('ascii')
'<foo/>'
但是,我有此 ASCII 字符串:
'\u003foo\u003e'
...我想将其转换为与上述第一个示例相同的 ASCII 字符串:
... that I want to turn into the same ASCII string as in my first example above:
'<foo/>'
推荐答案
我花了一些时间才弄清楚这一点,但是此页面具有最佳答案:
It took me a while to figure this one out, but this page had the best answer:
>>> s = '\u003cfoo/\u003e'
>>> s.decode( 'unicode-escape' )
u'<foo/>'
>>> s.decode( 'unicode-escape' ).encode( 'ascii' )
'<foo/>'
还有一个'raw-unicode-escape'编解码器,用于处理另一种指定Unicode字符串的方法-有关更多详细信息,请查看链接页面的"Unicode构造函数"部分(因为我不是那么喜欢Unicode的人)
There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the "Unicode Constructors" section of the linked page for more details (since I'm not that Unicode-saavy).
另请参见 Python标准编码.
这篇关于如何将ASCII字符串视为unicode,并在python中取消转义其中的转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!