python中的转义字符仅转义一次(单个)
我想从以下内容中转义一个字符串:python中的转义字符仅转义一次(单个),python,escaping,Python,Escaping,我想从以下内容中转义一个字符串: str1 = "this is a string (with parentheses)" 为此: str2 = "this is a string \(with parentheses\)" 也就是说,括号中只有一个\转义字符。这将被馈送到另一个客户端,该客户端需要转义这些字符,并且只能使用单个转义斜杠 为了简单起见,我在下面只关注左括号,即从'('更改为'\(' 到目前为止,我试过: 替换 str1.replace("(", "\(") 'this is
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在字符串文字表示中转义反斜杠,以防止它被解释为转义代码