Why doesn't this throw a SyntaxError instead of silently interpreting it wrong?

Go To StackoverFlow.com


There is supposed to be a comma between these two strings

foo = ['dumb'

But if you forget the comma, it just merges the strings together instead of producing a syntax error. Your result will be


I spent hours tracking this down. Why is the Python interpreter merging these strings?

2012-04-03 20:36
by Nathan
This is a documented behavior of the language. As to why it's a documented behavior of the language, ask Guido - kindall 2012-04-03 20:37
What python version - PenguinCoder 2012-04-03 20:37


It's a documented feature to allow for nicer formatting in source code with string literals.

Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings.


It is also worth remembering this note:

Note that this feature is defined at the syntactical level, but implemented at compile time. The ‘+’ operator must be used to concatenate string expressions at run time. Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings).

2012-04-03 20:38
by Gareth Latty
Well I definitely arrived at this feature from the wrong direction : - Nathan 2012-04-03 20:41


That's not a bug, it's a feature! Python is documented as concatenating strings with nothing but whitespace between them.


2012-04-03 20:38
by Mark Ransom