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 \"
?
UPDATE:
I need as output from this copyable text that shows both the quotes and the newlines as escaped. In other words, I want to be able to copy:
'This sentence has some \"quotes\" in it.\n'
If I use the raw string and print
the result I get the correctly escaped quote, but the escaped newline doesn't print. If I don't use print
then I get my newlines but double-escaped quotes. How can I create a string I can copy that shows both newline and quote escaped?
Copyright Notice:Content Author:「mix」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18886596/replace-all-quotes-in-a-string-with-escaped-quotes