0

I am running on Python 3.6.1 and today I missed a comma, as follows:

nt = namedtuple('Record', ['c', 'a' 'b'])
# instead the following is what I actually want
nt = namedtuple('Record', ['c', 'a', 'b'])

But I just wonder why the first way is valid Python in any way? Should not it complains with syntax error?

I just tried in 3.5.2 and 2.7.11. Seems all valid. But it is valid?

Junchao Gu
  • 1,815
  • 6
  • 27
  • 43

2 Answers2

0

From the Python tutorial:

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

>>> 'Py' 'thon'
'Python'
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • I have been working in Python for two years and this is the first time I know this. May I know what is the philosophy behind this? – Junchao Gu Jun 06 '18 at 08:48
  • It's in the link: it's useful for breaking up long strings over multiple lines. – Alex Hall Jun 06 '18 at 08:50
  • But in my case it is source of error. We have """""" format and ('' \n '') format already right – Junchao Gu Jun 06 '18 at 08:51
  • Well, i guess it is just design decision. I will just keep this in mind – Junchao Gu Jun 06 '18 at 08:53
  • 1
    No, triple quotes and `\n` are for creating strings that contain newlines. This is for long strings that don't contain newlines but need to be broken into multiple lines of source code to avoid very long lines of code. It simply removes the need for `+`. I agree the benefit is still not great and it can cause errors, I've been bitten by it before as well. I can't say why it was decided that the benefit outweighed the risks. Maybe it's because errors like this will usually be spotted very quickly. – Alex Hall Jun 06 '18 at 09:21
  • Thanks for your explanation – Junchao Gu Jun 07 '18 at 06:12
0

Python will concatenate adjacent strings which are delimited by whitespace: https://docs.python.org/2.0/ref/string-catenation.html

grahamlyons
  • 687
  • 5
  • 15