python中如何用\'替换单引号(')?

How to replace single quotes (') with \' in python?

如何在 python 中用 \' 替换单引号 (')

需要从

转换
"{'fr': '', 'en': 'Title Edit 02'}"

"{\'fr\': \'\', \'en\': \'Changed\'}"

谈话是廉价的。给你看代码

str = "{'fr': '', 'en': 'Title Edit 02'}"
str1 = str.replace("\'", "\\'")
print(str1)

输出

"{\'fr\': \'\', \'en\': \'Title Edit 02\'}"

试试下面的代码:

s = "{'fr': '', 'en': 'Title Edit 02'}"
s= s.replace("'","\'").strip("\'")
print(s) # Or Do What you need with s 

输出:{\'fr\': \'\', \'en\': \'Title Edit 02\'}

解释:将所有'替换为'。 strip() 可以省略,只是一个故障保险。