在python中转义字符只需一次(单个反冲)

ati*_*oSE 2 python escaping

我想逃避这个字符串:

str1 = "this is a string (with parentheses)"
Run Code Online (Sandbox Code Playgroud)

对此:

str2 = "this is a string \(with parentheses\)"
Run Code Online (Sandbox Code Playgroud)

也就是说,\括号中有一个转义字符.这将被提供给另一个需要转义这些字符的客户端,并且只能使用一个转义斜杠.

为简单起见,我只关注下面的开括号,即从'('改为'\(' 到目前为止我试过:

  1. 更换

    str1.replace("(", "\(")
    'this is a string \\(with parentheses)'
    
    Run Code Online (Sandbox Code Playgroud)
  2. re.sub( "\(", "\(", str1)
    'this is a string \\(with parentheses)'
    
    Run Code Online (Sandbox Code Playgroud)
  3. 逃生字典与原始字符串

    escape_dict = { '(':r'\('}
    "".join([escape_dict.get(char,char) for char in str1])
    'this is a string \\(with parentheses)'
    
    Run Code Online (Sandbox Code Playgroud)

无论如何,我总是得到双重反弹.有没有办法只获得一个?

Mar*_*ers 6

您将字符串表示与字符串混淆.双反斜杠是为了使字符串圆形可以; 您可以再次将值粘贴回Python.

实际的字符串本身只有一个反斜杠.

看一眼:

>>> '\\'
'\\'
>>> len('\\')
1
>>> print '\\'
\
>>> '\('
'\\('
>>> len('\(')
2
>>> print '\('
\(
Run Code Online (Sandbox Code Playgroud)

Python会转义字符串文字表示中的反斜杠,以防止它被解释为转义码.