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
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.
my_line = 'foo' 'bar'
is string concatenation.
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
It isn't inconsistent. Strings and integers have different methods.
Integer concatenation is meaningless.
String concatenation is a meaningful default behavior.
精彩评论