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

Mat*_*eex 6 python string character-encoding

我需要一种方法让我的函数在运行时接收一个字符串并删除反斜杠,同时保留它前面的字符。所以对于 \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'\"',
         '\0':r'\0',
         '\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
Run Code Online (Sandbox Code Playgroud)

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

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

小智 0

您可能需要使用一个名为 的函数来实现此目的repr()

\n

repr() 计算对象的 \xe2\x80\x9cofficial\xe2\x80\x9d 字符串表示(具有有关对象的所有信息的表示),str() 用于计算 \xe2\x80\x9cinformal\xe2 \x80\x9d 对象的字符串表示形式(对于打印对象有用的表示形式)。

\n

例子:

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

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

\n