从字符串中删除转义字符 [英] remove escape character from string

查看:126
本文介绍了从字符串中删除转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转这个字符串:

a = '\\a'

进入这个

b = '\a'

replace 似乎没有明显的方法可以做到这一点?

It doesn't seem like there is an obvious way to do this with replace?

更准确地说,我想更改反斜杠的转义以转义字符 a

To be more precise, I want to change the escaping of the backslash to escape the character a

推荐答案

字符 '\a' 是 ASCII BEL 字符, chr(7).

The character '\a' is the ASCII BEL character, chr(7).

在 Python 2 中进行转换:

To do the conversion in Python 2:

from __future__ import print_function
a = '\\a'
c = a.decode('string-escape')
print(repr(a), repr(c))

输出

'\\a' '\x07'

为了将来参考,在 Python 3 中:

And for future reference, in Python 3:

a = '\\a'
b = bytes(a, encoding='ascii')
c = b.decode('unicode-escape')
print(repr(a), repr(c))

这给出了与上述代码片段相同的输出.

This gives identical output to the above snippet.

在 Python 3 中,如果您使用的是字节对象,您会执行以下操作:

In Python 3, if you were working with bytes objects you'd do something like this:

a = b'\\a'
c = bytes(a.decode('unicode-escape'), 'ascii')
print(repr(a), repr(c))

输出

b'\\a' b'\x07'

正如 Antti Haapala 所提到的,如果源字符串也包含 unicode 字符,那么这种针对 Python 3 的简单策略将不起作用.在这种情况下,请参阅他的回答以获得更强大的解决方案.

As Antti Haapala mentions, this simple strategy for Python 3 won't work if the source string contains unicode characters too. In tha case, please see his answer for a more robust solution.

这篇关于从字符串中删除转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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