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']))
Share:
10,478
blokeley
Author by

blokeley

Updated on June 24, 2022

Comments

  • blokeley
    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
    blokeley about 7 years
    The Jupyter notebook automatically prints the last statement in each cell. Why does this not respect newlines but print() does?
  • vishes_shell
    vishes_shell about 7 years
    @blokeley it shows the value, but if you want special symbols to appear, such as '\n' then you need to print.
  • BrenBarn
    BrenBarn about 7 years
    @blokeley: No, it doesn't (not exactly), and yes you do. The notebook displays the repr of the last value, but print uses str, which is the difference you're seeing.
  • blokeley
    blokeley about 7 years
    OK thanks all for drawing the distinction. It's strange that pandas output prints OK with multiple lines. Hmmm
  • juanpa.arrivillaga
    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 call repr
  • BrenBarn
    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
    mins over 3 years
    Maybe it would be good to give some details about the difference between print and display, as the explanation is all about that. +1