Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace ' with \' in a string

Tags:

python

replace

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.

like image 506
Rao Avatar asked Dec 04 '22 12:12

Rao


2 Answers

"\'" 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
like image 103
Volatility Avatar answered Dec 21 '22 14:12

Volatility


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.

like image 45
Michael Seibt Avatar answered Dec 21 '22 14:12

Michael Seibt