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.
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.
"'"
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
>>> 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
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.
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.
"'"
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
>>> 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