Python: 如何在字符串中转义单引号
以下是 Python 代码,可以实现该功能:
string = 'I'm a string with 'single quotes' inside.'
# 查找单引号并在前面加上斜杠
string = string.replace("'", "\'")
print(string)
输出:
I\'m a string with \'single quotes\' inside.
在这个例子中,我们使用字符串的 replace() 方法来替换所有的单引号。第一个参数是要替换的字符,第二个参数是要替换成的字符。在这个例子中,我们将单引号替换为斜杠 + 单引号的组合,即 \'。
原文地址: https://www.cveoy.top/t/topic/mXLu 著作权归作者所有。请勿转载和采集!