在Python中将单引号替换为反斜杠单引号

3

我一直在尝试将单引号替换为反斜杠单引号。

我一直在尝试这样做,但结果是一个带有两个反斜杠和单引号的字符串,或者没有任何反斜杠和单引号。

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

上述结果为输出:牛顿法re.sub("'","\\'","Newton's method")的结果为Newton\\'s method 我需要Newton\'s method作为输出。
非常感谢您的帮助。
更新:
这是一个在解析后创建的字符串,并通过html表单传递。 这里"Newton's method"会导致问题,因为它会在get请求后使json变形。
{'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"Newton's method", '9': u'List of things named after Isaac Newton', '8': u'Bill Newton'}

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

3
\\ 只是表示 \ 的符号。 - thefourtheye
尝试这个 print re.sub("'","\\'","牛顿法") 当你只是做 re.sub("'","\\'","牛顿法") 时,它的 repr 被调用。 - The6thSense
print re.sub("'", "'","Newton's method")。你的输出确实只有一个反斜杠,而不是两个。 - Riyaz
单斜杠和双斜杠都会导致JSON格式错误。我原本以为是Python解释器显示的单引号被替换后返回了双斜杠的问题。 - Akshay Hazari
你如何将数据序列化为 JSON? - Aske Doerge
1个回答

2

您需要转义 \ 或使用原始字符串字面值:

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

顺便提一下,对于这种情况,您不需要使用正则表达式。 str.replace 就足够了:

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

更新

\\ 是Python中repr表示字符串中反斜杠字符的一种方式。如果你打印这个字符串,你会看到它是一个\

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

1
@SiHa,'\\' 是一个单字符字符串,而不是双 \ - falsetru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接