如何将"原始"字符串转换为普通字符串?

Wen*_*.Wu 17 python string rawstring python-3.x

在Python中,我有一个这样的字符串:

'\\x89\\n'
Run Code Online (Sandbox Code Playgroud)

如何将其解码为普通字符串,如:

'\x89\n'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 27

可以使用'string_escape'编解码器解码Python 2字节字符串:

raw_string.decode('string_escape')
Run Code Online (Sandbox Code Playgroud)

演示:

>>> '\\x89\\n'.decode('string_escape')
'\x89\n'
Run Code Online (Sandbox Code Playgroud)

对于unicode文字,请使用'unicode_escape'.在Python 3中,默认情况下字符串是unicode字符串,只有字节字符串有一个.decode()方法:

raw_byte_string.decode('unicode_escape')
Run Code Online (Sandbox Code Playgroud)

如果您的输入字符串已经是unicode字符串,请使用codecs.decode()转换:

import codecs

codecs.decode(raw_unicode_string, 'unicode_escape')
Run Code Online (Sandbox Code Playgroud)

演示:

>>> b'\\x89\\n'.decode('unicode_escape')
'\x89\n'
>>> import codecs
>>> codecs.decode('\\x89\\n', 'unicode_escape')
'\x89\n'
Run Code Online (Sandbox Code Playgroud)

  • 这在python3中不起作用。(`str`没有`decode`方法,而且`string_escape`不再是有效的编码)。 (2认同)

Iva*_*rak 8

这适用于Python 3:

b'\\x89\\n'.decode('unicode_escape')
Run Code Online (Sandbox Code Playgroud)