7

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
3
  • 3
    You need to actually print(...) it... Commented May 7, 2017 at 18:33
  • 1
    @juanpa.arrivillaga word for word...:) Commented May 7, 2017 at 18:35
  • Adding to @juanpa.arrivillaga,in python3, don't forget to include brackets to while printing or you will get an error. Commented May 7, 2017 at 18:36

1 Answer 1

10

You need to actually print it.

import os
print(os.linesep.join(['first line', 'second line']))
Sign up to request clarification or add additional context in comments.

7 Comments

The Jupyter notebook automatically prints the last statement in each cell. Why does this not respect newlines but print() does?
@blokeley it shows the value, but if you want special symbols to appear, such as '\n' then you need to print.
@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.
OK thanks all for drawing the distinction. It's strange that pandas output prints OK with multiple lines. Hmmm
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.