Replace ' with ' in a string

Question:

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.

Asked By: Rao

||

Answers:

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.

Answered By: Michael Seibt

"'" 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
Answered By: Volatility
>>> str = r"This is a 'test' string"
>>> print str
This is a 'test' string
>>> str.replace("'","\'")
"This is a \'test\' string"

You need to escape the special character

Answered By: Tuxdude
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.