0

I recently stumbled across a problem in Python 2.7.9. I defined a list of strings, but I forgot to set a comma on one item like this:

myList = ["a", "b", "c" "d"]

which results in this list:

["a", "b", "cd"]

I guessed that Python effectively inserted a + operator and was curious what would happen in similar cases, e.g.:

[1,2,3 4]

but Python just tells me that this is invalid syntax (as I expected for the first case, too).

So why does Python concatenate strings if NO operator is defined between them? Is there a good use case, where omitting the + operator has benefits?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Rafael T
  • 15,401
  • 15
  • 83
  • 144
  • This has already been asked. See : http://stackoverflow.com/questions/18842779/string-concatenation-without-operator-in-python – rafaelc Apr 14 '15 at 13:35
  • Because that's what the language reference says it should do: https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation *"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..."* See also http://stackoverflow.com/a/29559961/3001761, where I recently found a (slightly hacky!) alternative use for it. – jonrsharpe Apr 14 '15 at 13:35
  • string concatenation. an idea borrowed from C-like languages. – Karoly Horvath Apr 14 '15 at 13:46

0 Answers0