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

Go To StackoverFlow.com

1

There is supposed to be a comma between these two strings

foo = ['dumb'
'error']

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

['dumberror']

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


6

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.

Source

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


1

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

http://docs.python.org/release/2.5.2/ref/string-catenation.html

2012-04-03 20:38
by Mark Ransom