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

2024-05-15 14:35:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从这里逃出一条线:

str1 = "this is a string (with parentheses)"

为此:

^{pr2}$

也就是说,括号中有一个\转义字符。这将被传送到另一个需要转义这些字符的客户机,并且只使用一个转义斜杠。在

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

  1. 更换

    str1.replace("(", "\(")
    'this is a string \\(with parentheses)'
    
  2. sub公司

    re.sub( "\(", "\(", str1)
    'this is a string \\(with parentheses)'
    
  3. 带原始字符串的转义字典

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

不管怎样,我总是受到双重反对。有没有办法只得到一个?在


Tags: 客户机stringiswiththis字符dict括号
1条回答
网友
1楼 · 发布于 2024-05-15 14:35:42

您将字符串表示与字符串混淆。双反斜杠是为了使字符串可以进行四舍五入;您可以再次将值粘贴回Python。在

实际字符串本身只有一个反斜杠。在

看看:

>>> '\\'
'\\'
>>> len('\\')
1
>>> print '\\'
\
>>> '\('
'\\('
>>> len('\(')
2
>>> print '\('
\(

Python在字符串文本表示中对反斜杠进行转义,以防止反斜杠被解释为转义代码。在

相关问题 更多 >