Search code examples
pythonstringescapingquoteslexical-analysis

lexical analysis python


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.


Solution

  • 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 "":

    x = '\''
    y = "\""
    

    EDIT :

    Regarding the last part in the question, added after the edit:

    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

    Any of the following will work, notice the use of raw strings for avoiding the need to escape special characters:

    v = "\\'"
    w = '\\\''
    x = r'\''
    y = r"\'"
    
    print v, w, x, y
    > \' \' \' \'