How to convert a “raw” string into a normal string?

ぐ巨炮叔叔 提交于 2019-11-26 21:12:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!