I have a string:
s = r"This is a 'test' string"
I am trying to replace ' with \' so the string will look like below:
s = r"This is a \'test\' string"
I tried s.replace("'","\'") but there is no change in result. It remains the same.
"\'" is still the same as "'" - you have to escape the backslash.
mystr = mystr.replace("'", "\\'")
Making it a raw string r"\'" would also work.
mystr = mystr.replace("'", r"\'")
Also note that you should never use str (or any other builtin name) as a variable name since it will overwrite the builtin, and could cause confusion later on when you try to use the builtin.
>>> mystr = "This is a 'test' string"
>>> print mystr.replace("'", "\\'")
This is a \'test\' string
>>> print mystr.replace("'", r"\'")
This is a \'test\' string
You have to escape the "\":
str.replace("'","\\'")
"\" is an escape sequence indicator, which, to be used as a normal char, has to be escaped (by) itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With