-2

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

Need to convert from

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

to

"{\'fr\': \'\', \'en\': \'Changed\'}"
Thirumal
  • 8,280
  • 11
  • 53
  • 103

2 Answers2

2

Try the following code:

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

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

Explanation: Replace all ' with '. strip() can be omitted, just a fail safe.

Sayok Majumder
  • 1,012
  • 13
  • 28
-1

Talk is cheap. Show you the code

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

OUT

"{\'fr\': \'\', \'en\': \'Title Edit 02\'}"
Kaia
  • 862
  • 5
  • 21