Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的转义字符仅转义一次(单个)_Python_Escaping - Fatal编程技术网

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在字符串文字表示中转义反斜杠,以防止它被解释为转义代码