0

Python:在字符串中,例如“Hi”5“Hello”,我想在双引号前插入(反斜杠)。对于上面的例子,我想插入“Hi\”5\“Hello”。有没有办法在python中做到这一点。

我有以下形式的数据:

   <a> <b> "Hi"5"Hello"
   <c> <d> ""Way"toGo"

我想将此数据转换为以下形式:

   <a> <b> "Hi\"5\"Hello"
   <c> <d> "\"Way\"toGo"
4

2 回答 2

2

如果我理解正确,您想转义"字符串中除第一个和最后一个之外的所有内容。如果这是真的,那么我们会得到类似的东西:

>>> i1 = s.index('"')
>>> i2 = s.rindex('"')
>>> i1
0
>>> i2
11
>>> s[i1+1:i2]
'Hi"5"Hello'
>>> ''.join((s[:i1+1],s[i1+1:i2].replace('"',r'\"'),s[i2:]))
'"Hi\\"5\\"Hello"'
于 2013-04-29T14:37:07.140 回答
0

很容易迷失在字符转义规则中,尤其是当您在 Python、JavaScript、正则表达式语法等之间切换时。在 Python 中执行此操作的简单方法是使用“r”表示法将您的字符串标记为“原始”:

不好的例子:

>>> test = 'Hi \there \\friend \n good day'
>>> print test
Hi      here \friend 
 good day

好的例子:

>>> test = r'Hi \there \\friend \n good day'
>>> print test
Hi \there \\friend \n good day
于 2013-04-29T16:48:17.883 回答