在运行时删除Python中的反斜杠



我需要一种方法让我的函数在运行时接收一个字符串,并删除反斜杠,同时保留它前面的字符。所以对于\a,我必须得到a。这也必须适用于像\e->e.

我在互联网上搜索过这个问题的一般解决方案,但似乎没有。我找到的最好的解决方案是使用字典从头开始构建字符串,比如:如何防止Python 中特殊字符的自动转义

escape_dict={'a':r'a',
'b':r'b',
'c':r'c',
'f':r'f',
'n':r'n',
'r':r'r',
't':r't',
'v':r'v',
''':r''',
'"':r'"',
'':r'',
'1':r'1',
'2':r'2',
'3':r'3',
'4':r'4',
'5':r'5',
'6':r'6',
'7':r'7',
'8':r'8',
'9':r'9'}
def raw(text):
"""Returns a raw string representation of the string"""
new_string=''
for char in text:
try: 
new_string += escape_dict[char]
except KeyError: 
new_string += char
return new_string

然而,由于转义数字和转义字母之间的冲突,这通常会失败。使用像\001这样的3位数字代替\1也会失败,因为输出中会有额外的数字,这会破坏目的。我应该简单地删除反斜杠。其他提出的基于编码的解决方案,如在Python 中处理字符串中的转义序列

也不起作用,因为这只是将转义字符转换为十六进制代码。\a被转换为\x07。即使以某种方式删除了这个字符a仍然丢失。

您可能想要为此目的使用一个名为repr()的函数。

repr((计算对象的"官方"字符串表示(一种包含对象所有信息的表示(,str((用于计算对象的非正规字符串表示(用于打印对象的表示(。

示例:

s = 'This is a t string tab. And this is a n newline character'
print(s)  # This will print `s` with a tab and a newline inserted in the string
print(repr(s))  # This prints `s` as the original string with backslash and the whatever letter you have used
# So maybe you can use this somewhere
print(repr(s).replace('\', '_'))
# And obviously this might not have worked for you
print(s.replace('\', '_'))

因此,您可以使用repr(<your string>)替换字符串中的反斜杠

最新更新