Python,用新模式替换所有单引号/双引号

时间:2015-09-15 06:14:47

标签: python regex

这是一个nodejs regexp,它将两个引号替换为json解析器接受的新模式。

async: false

输出,

var someStr = "this string has one single quote ': this string has a double quote \""
console.log(someStr.replace(/'|"/g, '\\\\\\"'))

我很高兴。但在python中,我将其翻译为,

this string has one single quote \\\": this string has a double quote \\\"

但它输出,

import re
someStr = "this string has one single quote ': this string has a double quote \""
output = re.sub("'|\"",r"\\\"", someStr)

为什么python原始字符串的三个反斜杠被写为双反斜杠?

2 个答案:

答案 0 :(得分:4)

这是变量输出真正包含的内容:

 'this string has one single quote \\\\": this string has a double quote \\\\"'

但是\是python中的转义字符串,例如\\如果你打印它会产生\。

答案 1 :(得分:2)

这是因为正则表达式替换也使用\ escapes,将它们扩展为\ n,其中n是数字,指的是子组。例如:

>>> re.sub(r"a", r"\r", "cat")
'c\rt'
>>> r"\r"
'\\r'
>>> re.sub(r"(a)", r"\1\1", "cat")
'caat'

因此,即使使用原始字符串,在使用re.sub时也需要转义反斜杠。