Search code examples
pythonstringpython-2.7quotes

So what is the story with 4 quotes?


I was experimenting in the python shell with the type() operator. I noted that:

type('''' string '''') 

returns an error which is trouble scanning the string

yet:

type(''''' string ''''')

works fine and responds that a string was found.

What is going on? does it have to do with the fact that type('''' string '''') is interpreted as type("" "" string "" "") and therefore a meaningless concatenation of empty strings and an undefined variable?


Solution

  • You are ending a string with 3 quotes, plus one extra. This works:

    >>> ''''string'''
    "'string"
    

    In other words, Python sees 3 quotes, then the string ends at the next 3 quotes. Anything that follows after that is not part of the string anymore.

    Python also concatenates strings that are placed one after the other:

    >>> 'foo' 'bar'
    'foobar'
    

    so '''''string''''' means '''''string''' + '' really; the first string starts right after the opening 3 quotes until it finds 3 closing quotes. Those three closing quotes are then followed by two more quotes forming a separate but empty string:

    >>> '''''string'''
    "''string"
    >>> '''''string'''''
    "''string"
    >>> '''''string'''' - extra extra! -'
    "''string - extra extra! -"
    

    Moral of the story: Python only supports triple or single quoting. Anything deviating from that can only lead to pain.