I always thought that in order to get a new line in my standard output I need to add '\\n' inside my print statement. But recently I came across the following expression:
print("Hello"),'\n',print("World")
Which works just like:
print("Hello\nWorld")
Can someone explain how the '\\n' works outside the print function and yet my standard output knows to get a new line? Also what is the meaning of the comma symbols in the first expression which are also outside the print function?
print('Hello'),'\n',print('World')
and
print('Hello\nWorld')
are not equivalent.
The first is an expression which returns a tuple of (NoneType, str, NoneType)
(because \\n
is a string and the print
function returns None
, which has type NoneType
). However, this expression has the side effect of also printing first Hello
then World
to stdout. Since print, by default, puts a newline at the end of each invocation, this will appear as
Hello
World
in stdout.
The second is simply an expression that prints Hello\\nWorld
to stdout, which (since \\n
is the newline character) also appears as
Hello
World
in stdout.
At a REPL (or jupyter notebook, or similar), you will get:
>>> print('Hello'),'\n',print('World')
Hello
World
(None, '\n', None)
>>> print('Hello\nWorld')
Hello
World
this is because default behaviour is for the REPL to print the value that your expression evaluates to, unless that value is None
. So in the first case it executes the two print
functions (getting Hello\\nWorld
on stdout) then prints the expression's value, the tuple (None, '\\n', None)
.
on my jupyter-notebook I get:
Hello
World
(None, '\n', None)
so print("Hello"),'\\n',print("World")
it is not the same as print("Hello\\nWorld")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.