1

If you forget a comma in a list of strings, Python (2.7) will automatically concatenate the two strings. For example:

x = ['id', 'date' 'time']
print(x)
#[id, 'datetime']

This behavior seems to run contrary to the vast majority of "use cases" where a user simply forgot the comma. This leads to either missing an error in the code or getting an odd error message. In the example above, for instance, this was a list of attributes for an object and it threw AttributeError: 'YourObjectClass' object has no attribute 'datetime'. Is this a feature or a bug, and if it's a feature why is it a feature?

smci
  • 32,567
  • 20
  • 113
  • 146
Michael
  • 13,244
  • 23
  • 67
  • 115
  • 2
    This behavior is not only in list. Try `x = 'date' 'time'` – Tuan Anh Hoang-Vu Jun 18 '15 at 18:47
  • In C: To permit more flexible layout, and to solve some preprocessing problems, the C89 Committee introduced string literal concatenation. Two string literals in a row are pasted together, with no null character in the middle, to make one combined string literal __...This addition to the C language allows a programmer to extend a string literal beyond the end of a physical line without having to use the backslash–newline mechanism__" I suspect Python has the same reasoning, ie to reduce ugly \ to continue long string literals. – Burkely91 Jun 18 '15 at 20:06

2 Answers2

2

It's a feature, and its rationale is given in the part of the spec that describes it:

Multiple adjacent string 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, for example:

re.compile("[A-Za-z_]"       # letter or underscore
           "[A-Za-z0-9_]*"   # letter, digit or underscore
          )
Community
  • 1
  • 1
jwodder
  • 54,758
  • 12
  • 108
  • 124
1

This is a feature called string literal concatenation.

String literal concatenation

Multiple adjacent string 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:

re.compile("[A-Za-z_]"       # letter or underscore
           "[A-Za-z0-9_]*"   # letter, digit or underscore
          )

This feature is defined at the syntactical level, but implemented at compile time.

Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126