Question

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?

Was it helpful?

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.

OTHER TIPS

Your supposition seems to be correct, given the following:

a = '''' string ''''
  File "<stdin>", line 1
    a = '''' string ''''
                       ^
SyntaxError: EOL while scanning string literal

As Martijn says in his answer, Python is trying to concatenate adjacent strings, and fails when it doesn't find the ending '.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top