Joonho Park
Joonho Park

Reputation: 563

python - print newline sometimes does not work. Why?

in python 2.7

print("hello\nJoonho")

prints

"hello

Joonho"

But

a=3
print(a, "\nhello\nJoonho")

prints

"(3, "\nhello\nJoonho")

Would you explain why this is happening? "print()" is not a function? And how to pass by this problem?

Upvotes: 3

Views: 11413

Answers (3)

Fábio Perez
Fábio Perez

Reputation: 26108

In Python 2, print is a statement. So, by calling print(a, "\nhello\nJoonho"), you are printing the tuple (a, "\nhello\nJoonho").

You can use the print() function in Python 2 by importing it from the future:

from __future__ import print_function

The print statement converts the the object to a string before printing it:

print evaluates each expression in turn and writes the resulting object to standard output (see below). If an object is not a string, it is first converted to a string using the rules for string conversions.

So, in print ("hello\nJoonho"), the object ("hello\Joonho") will be converted to a string (("hello\nJoonho").__str__(), which results in 'hello\nJoonho'). Then, the string 'hello\nJoonho' will be printed.

In print (a, "\nhello\nJoonho"), (a, "\nhello\nJoonho") will be converted to a string ((a, "\nhello\nJoonho").__str__(), which results in "(3, '\\nhello\\nJoonho')"). Then, the string "(3, '\\nhello\\nJoonho')" will be printed. Note that when the second tuple is converted to a string, the \n are escaped.

Upvotes: 1

MohitC
MohitC

Reputation: 4821

print always gives you the printable representation of the object being printed on stdout. When you say print(a, "\nhello\nJoonho"), here (a, "\nhello\nJoonho") is a tuple and hence represented as tuple object.

To get more clarity on this: If you do print(a, "\nhello\nJoonho")[1] then it actually gets printed as

>>> print(0, '\nhello\nJoonho')[1]

hello
Joonho

since object denoted by [1] is a string and \n are converted to new line on stdout for string objects.

Upvotes: 5

timakro
timakro

Reputation: 1851

Before python 3 print was not a function. In python 3 print is a function.

You can translate python 2.7

print(a, "\nhello\nJoonho")

to python 3

print((a, "\nhello\nJoonho"))

So your statement actually prints the representation of the tuple.

That is because when you pass a string to the print function it is printed as it is. If you pass anything else to the print function, for example a tuple its representation is printed. You can also get the representation of an object by using the repr function:

>>> repr((a, "\nhello\nJoonho"))
"(3, '\\nhello\\nJoonho')"

The representation of an object is normally a valid python expression.

Upvotes: 1

Related Questions