Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 672
Sidharth Ghoshal Avatar asked Nov 12 '13 18:11

Sidharth Ghoshal


1 Answers

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.

like image 169
Martijn Pieters Avatar answered Oct 19 '22 07:10

Martijn Pieters