Python:带斜杠的转义引号

2024-04-26 10:58:04 发布

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

我试图在Python中避开引号,但我的计划行不通:

>>> s = 'Hi "there"'

>>> s.replace('"', '\"')
'Hi "there"'

>>> s.replace('"', '\\"')
'Hi \\"there\\"'

在字符串中使用单转义引号的正确方法是什么(例如,make'Hi \"there\"')?你知道吗


Tags: 方法字符串makehireplace引号计划there
1条回答
网友
1楼 · 发布于 2024-04-26 10:58:04

你的代码是正确的。显示的字符串是repr(your_result)的结果,它包含自己的转义。你可以通过打印得到实际值。你知道吗

>>> result = s.replace('"', '\\"')

>>> result
'Hi \\"there\\"'

>>> print(result)
Hi \"there\"

>>> print(repr(result))
'Hi \\"there\\"'

相关问题 更多 >