问题
In Python, I have a string like this:
'\\x89\\n'
How can I decode it into a normal string like:
'\x89\n'
回答1:
Python 2 byte strings can be decoded with the 'string_escape'
codec:
raw_string.decode('string_escape')
Demo:
>>> '\\x89\\n'.decode('string_escape')
'\x89\n'
For unicode literals, use 'unicode_escape'
. In Python 3, where strings are unicode strings by default, only byte strings have a .decode()
method:
raw_byte_string.decode('unicode_escape')
If your input string is already a unicode string, use codecs.decode()
to convert:
import codecs
codecs.decode(raw_unicode_string, 'unicode_escape')
Demo:
>>> b'\\x89\\n'.decode('unicode_escape')
'\x89\n'
>>> import codecs
>>> codecs.decode('\\x89\\n', 'unicode_escape')
'\x89\n'
回答2:
This would work for Python 3:
b'\\x89\\n'.decode('unicode_escape')
来源:https://stackoverflow.com/questions/24242433/how-to-convert-a-raw-string-into-a-normal-string