Reputation: 9035
I was writing a simple Hello World Python script and tried a couple different things to see what I would get.
Results:
print "Hello World" ===> Hello World
print "Hello"," ","World ===> Hello World
print "Hello" "World" ===> HelloWorld
The results surprised me... from experience with other languages I expected to get something more like this:
print "Hello World" ===> Hello World
print "Hello"," ","World ===> Hello World
print "Hello" "World" ===> Syntax Error!
After trying a couple more examples I realized that it seems to add a space whenever you separate strings with a ",".
...Even more strangely, it doesn't seem to care if you give it multiple strings without a "," separating them as the third example shows.
Why does Python's print function act this way???
Also is there a way to stop it from adding spaces for "," separated strings?
Upvotes: 2
Views: 142
Reputation: 1121226
Because the print
statement adds spaces between separate values, as documented:
A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line.
However, "Hello" "World"
is not two values; it is one string. Only whitespace between two string literals is ignored and those string literals are concatenated (by the parser):
>>> "Hello" "World"
"HelloWorld"
See the String literal concatenation section:
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation.
This makes it easier to combine different string literal styles (triple quoting and raw string literals and 'regular' string literals can all be used to create one value), as well as make creating a long string value easier to format:
long_string_value = (
"This is the first chuck of a longer string, it fits within the "
'limits of a "style guide" that sets a shorter line limit while '
r'at the same time letting you use \n as literal text instead of '
"escape sequences.\n")
This feature is in fact inherited from C, it is not a Python invention.
In Python 3, where print()
is a function rather than a statement, you are given more control over how multiple arguments are handled. Separate arguments are delimited by the sep
argument to the function, which defaults to a space.
In Python 2, you can get the same functionality by adding from __future__ import print_function
to the top of your module. This disables the statement, making it possible to use the same function in Python 2 code.
Upvotes: 6