Wednesday 18 September 2013

Replace all quotes in a string with escaped quotes? python

Replace all quotes in a string with escaped quotes? python

Given a string in python, such as:
s = 'This sentence has some "quotes" in it\n'
I want to create a new copy of that string with any quotes escaped (for
further use in Javascript). So, for example, what I want is to produce
this:
'This sentence has some \"quotes\" in it\n'
I tried using replace(), such as:
s.replace('"', '\"')
but that returns the same string. So then I tried this:
s.replace('"', '\"')
but that returns double-escaped quotes, such as:
'This sentence has some \\"quotes\\" in it.\n'
How to replace " with \"?

No comments:

Post a Comment