Recently I made the following observation:
>>> x= "\'"
>>> x
"'"
>>> y="'"
>>> y
"'"
>>> print x
'
>>> print y
'
Can anyone please explain why is it so. I am using python 2.7.x. I know well about escape sequences.
I want to do the following:
I have a string with single quotes in it and I have to enter it in a database so I need to replace the instance of single quote(‘) with a backslash followed by a single quote(\’). How can I achieve this.
Inside a pair of
"", you don’t need to escape the'character. You can, of course, but as you’ve seen it’s unnecessary and has no effect whatsoever.It’d be necessary to escape if you were to write a
'inside a pair of''or a"inside a pair of"":EDIT :
Regarding the last part in the question, added after the edit:
Any of the following will work, notice the use of raw strings for avoiding the need to escape special characters: