在python中用反斜杠单引号替换单引号

2024-04-29 11:50:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图用反斜杠单引号替换单引号。在

我已经尝试过了,但是结果是一个字符串中有两个反斜杠和单引号,或者没有任何反斜杠和单引号。在

re.sub("'","\'","Newton's method")

以上结果为O/p:Newton's method

{{cd2>

我需要Newton\'s method作为输出。在

感谢任何帮助。在

更新:

这是一个在解析后创建的字符串,并使用html表单传递。在这里,"Newton's method"会导致一个问题,因为它会在get请求之后使json变形。在

^{pr2}$

html表单通过get请求获取此信息,而后端获取错误。在

 {'1': u'Newton metre', '0': u'Newton', '3': u'Newton (unit)', '2': u'Newton Centre, Massachusetts', '5': u'NewtonCotes formulas', '4': u'.30 Newton', '7': u'Newton Highlands, Massachusetts', '6': u

Tags: 字符串rejson表单gethtmlnewtonmethod
1条回答
网友
1楼 · 发布于 2024-04-29 11:50:26

您需要转义\或使用原始字符串文本:

>>> re.sub("'", "\\'","Newton's method")
"Newton\\'s method"
>>> re.sub("'", r"\'","Newton's method")
"Newton\\'s method"

顺便说一句,对于这种情况,您不需要使用正则表达式。^{}就够了:

^{pr2}$

更新

\\是pythonrepr表示字符串中反斜杠字符的一种方式。如果打印字符串,您将看到它是一个\。在

>>> "Newton\\'s method"
"Newton\\'s method"
>>> print("Newton\\'s method")
Newton\'s method

相关问题 更多 >