gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:13:41 27 4
gpt4 key购买 nike

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

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

它输出,

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

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

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

但是它输出,

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

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

最佳答案

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

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

但\是 python 中的转义字符串,例如\\如果您打印它会导致\。

关于Python,用新模式替换所有单引号/双引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32578918/

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