Boris Gorelik
Boris Gorelik

Reputation: 31767

Syntax quirks or why is that valid python

In python 2.6, why is the following line valid?

my_line = 'foo' 'bar'

and if that is valid, why isn't the following:

my_list = 1 2 

The first example is string concatenation, however, the following isn't valid either (thanks god):

foo = 'foo'
bar = 'bar'
foo_bar = foo bar

Upvotes: 8

Views: 3300

Answers (4)

Peter Hansen
Peter Hansen

Reputation: 22057

This is doing string literal concatenation. As noted in the documentation, advantages include the following:

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...

It goes on to note that this concatenation is done at compilation time rather than run time.

The history and rationale behind this, and a rejected suggestion to remove the feature, is described in PEP 3126.

Upvotes: 20

Eli Bendersky
Eli Bendersky

Reputation: 273496

Perhaps this is of C's ancestry. In C, the following is perfectly valid:

char* ptr = "hello " "world";

It is implemented by the C pre-processor (cpp), and the rationale given in that link is:

this allows long strings to be split over multiple lines, and also allows string literals resulting from C preprocessor defines and macros to be appended to strings at compile time

Upvotes: 6

S.Lott
S.Lott

Reputation: 391852

It isn't inconsistent. Strings and integers have different methods.

Integer concatenation is meaningless.

String concatenation is a meaningful default behavior.

Upvotes: 5

jldupont
jldupont

Reputation: 96736

my_line = 'foo' 'bar' is string concatenation.

Upvotes: 8

Related Questions