AllTradesJack
AllTradesJack

Reputation: 2882

Python 2.7: What print() does to the string inside of it

I've been using the print() syntax in my python 2.7 files even though I know that in 2.7 print is a statement, and not a function like in 3.X. But the python interpreter didn't seem to have any problem with the print() syntax, so I kept it to make a possible future port to 3.X easier. But I noticed something fishy about the way Python was treating the string literal inside the parenthesis:

>>>> print("\nFirst line\n", "Second line")

('\First line\n', 'Second line')  

Whereas the typical 2.7 statement syntax prints the newline characters as expected:

>>>>print "\nFirst line\n", "Second line"

First line
Second line

Question:

So whats the reasoning behind the print() working in 2.7 but ignoring the \n character? It is almost like print() is printing out the __repr__ string of the contained string literal.

Upvotes: 0

Views: 291

Answers (1)

kindall
kindall

Reputation: 184201

You can surround any expression with parentheses without changing its value, so:

print ("hello world")

is exactly the same as:

print "hello world"

It looks like a function call at first blush, but in fact you are simply printing a string expression that happens to be in parentheses. Same deal as this:

x = 1 + 2   # same as
x = (1 + 2)

However, if you try to print multiple items, or print with a comma at the end of your string (which is often used ot avoid printing the newline), you will get the kind of results you're describing:

print ("hello", "world")
print ("hello world",)

In this case you are printing a tuple.

t = ("hello", "world")   # or
t = ("hello world", )

print t

And printing a tuple does in fact print the repr() of each item within it.

Upvotes: 5

Related Questions