Reputation: 31767
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
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
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
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