我想从中转义一个字符串:
str1 = "this is a string (with parentheses)"
对此:
str2 = "this is a string (with parentheses)"
也就是说,括号中的单个转义字符。这将提供给另一个需要转义这些字符的客户端,并且只能使用单个转义斜杠。
为简单起见,我在下面只关注左括号,即从'('
更改为'('
到目前为止,我尝试了:
取代
str1.replace("(", "(") 'this is a string \(with parentheses)'
子
re.sub( "(", "(", str1) 'this is a string \(with parentheses)'
包含原始字符串的转义字典
escape_dict = { '(':r'('} "".join([escape_dict.get(char,char) for char in str1]) 'this is a string \(with parentheses)'
无论如何,我总是受到双重反弹。有没有办法只得到一个?
您将字符串表示形式与字符串值混淆了。双反斜杠用于使字符串可循环跳闸;您可以再次将该值粘贴回 Python 中。
实际字符串本身只有一个反斜杠。
看看:
>>> '\'
'\'
>>> len('\')
1
>>> print '\'
>>> '('
'\('
>>> len('(')
2
>>> print '('
(
Python 在字符串文字表示形式中转义反斜杠,以防止它被解释为转义代码。