Print multiple line string in Jupyter notebook
10,478
You need to actually print
it.
import os
print(os.linesep.join(['first line', 'second line']))
Author by
blokeley
Updated on June 24, 2022Comments
-
blokeley almost 2 years
I'm trying to print a multiple line string to a Jupyter notebook. The problem is that \r and \n are printed literally and not interpreted as newlines.
Example:
import os os.linesep.join(['first line', 'second line'])
I would expect this to print:
first line second line
But it prints:
first line\r\nsecond line
-
blokeley about 7 yearsThe Jupyter notebook automatically prints the last statement in each cell. Why does this not respect newlines but print() does?
-
vishes_shell about 7 years@blokeley it shows the value, but if you want special symbols to appear, such as
'\n'
then you need toprint
. -
BrenBarn about 7 years@blokeley: No, it doesn't (not exactly), and yes you do. The notebook displays the
repr
of the last value, butprint
usesstr
, which is the difference you're seeing. -
blokeley about 7 yearsOK thanks all for drawing the distinction. It's strange that pandas output prints OK with multiple lines. Hmmm
-
juanpa.arrivillaga about 7 years@blokeley why is it strange? Look at the
repr(some_dataframe)
. In other words, the issue isn't newlines per se, but how strings represent newlines when you callrepr
-
BrenBarn about 7 years@blokeley: The
repr
of a dataframe is a string with some newlines in it. The repr of a string with a newline in it is a string with a blackslash in it. What you get when you display the pandas value is the repr of the DataFrame, not the repr of the string that is the repr of the DataFrame. -
mins over 3 yearsMaybe it would be good to give some details about the difference between
print
anddisplay
, as the explanation is all about that. +1