gpt4 book ai didi

python - 仅一次转义 python 中的字符(单反冲)

转载 作者:行者123 更新时间:2023-11-28 21:22:09 24 4
gpt4 key购买 nike

我想从中转义一个字符串:

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

为此:

str2 = "this is a string \(with parentheses\)"

即,括号中的单个 \ 转义字符。这将被提供给另一个需要转义这些字符的客户端,并且只能使用一个转义斜杠。

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

  1. 替换

    str1.replace("(", "\(")
    'this is a string \\(with parentheses)'
  2. 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)'

无论如何,我总是遭到双重反对。有没有办法只得到一个?

最佳答案

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

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

看看:

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

Python 对字符串文字表示中的反斜杠进行转义,以防止将其解释为转义码。

关于python - 仅一次转义 python 中的字符(单反冲),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19833025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com