可以使用 replace() 函数将字符串中的单引号替换为转义字符 '' + 单引号。示例如下:

string = 'I'm a string with a ' in it'
new_string = string.replace("'", "\'")
print(new_string)

输出结果为:

I'm a string with a \' in it

replace() 函数中,第一个参数为要被替换的字符,第二个参数为替换后的字符。由于转义字符 '' 本身也需要被转义,所以要在其前面加上一个转义字符 ''。

Python 字符串替换单引号为转义字符

原文地址: https://www.cveoy.top/t/topic/lKDr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录