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?

3
  • 1
    'a' 'b' is 'ab' which is valid Commented Jun 5, 2018 at 10:42
  • Yes, consecutive string literals are concatenated. Just like in C or several other languages. Commented Jun 5, 2018 at 10:43
  • 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? @MartijnPieters I believe it is a source a bug -- it should just tell me syntax error in my opinion Commented Jun 6, 2018 at 8:49

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

6 Comments

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?
It's in the link: it's useful for breaking up long strings over multiple lines.
But in my case it is source of error. We have """""" format and ('' \n '') format already right
Well, i guess it is just design decision. I will just keep this in mind
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.
|
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.