如何转换“原始"文件字符串变成普通字符串? [英] How to convert a "raw" string into a normal string?

查看:48
本文介绍了如何转换“原始"文件字符串变成普通字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

'\\x89\\n'

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

'\x89\n'

解决方案

如果您的输入值为 str 字符串,请使用 codecs.decode() 进行转换:

导入编解码器codecs.decode(raw_unicode_string, 'unicode_escape')

如果您的输入值是 bytes 对象,您可以使用 bytes.decode() 方法:

raw_byte_string.decode('unicode_escape')

演示:

<预><代码>>>>导入编解码器>>>codecs.decode('\\x89\\n', 'unicode_escape')'\x89\n'>>>b'\\x89\\n'.decode('unicode_escape')'\x89\n'

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

<预><代码>>>>导入系统;sys.version_info[:2](2, 7)>>>'\\x89\\n'.decode('string_escape')'\x89\n'

对于 Unicode 文字(带有 u 前缀,例如 u'\\x89\\n'),使用 'unicode_escape'.

In Python, I have a string like this:

'\\x89\\n'

How can I decode it into a normal string like:

'\x89\n'

解决方案

If your input value is a str string, use codecs.decode() to convert:

import codecs

codecs.decode(raw_unicode_string, 'unicode_escape')

If your input value is a bytes object, you can use the bytes.decode() method:

raw_byte_string.decode('unicode_escape')

Demo:

>>> import codecs
>>> codecs.decode('\\x89\\n', 'unicode_escape')
'\x89\n'
>>> b'\\x89\\n'.decode('unicode_escape')
'\x89\n'

Python 2 byte strings can be decoded with the 'string_escape' codec:

>>> import sys; sys.version_info[:2]
(2, 7)
>>> '\\x89\\n'.decode('string_escape')
'\x89\n'

For Unicode literals (with a u prefix, e.g. u'\\x89\\n'), use 'unicode_escape'.

这篇关于如何转换“原始"文件字符串变成普通字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆