javaluv21
javaluv21

Reputation: 125

Python Newline \n not working in jupyter notebooks

I'm trying to display the tuples of a postgreSQL table neatly in my Jupyter Notebook, but the newline \n escape character doesn't seem to work here (it works for my python scripts w/ same code outside of jupyter).

I'm trying to run:

cur.execute('SELECT * FROM Cars')
'\n '.join(str(x) for x in cur.fetchall())

But my output still contains the '\n' characters themselves:

"(1, 'Toyota', 'Supra', 2020, 'Sport', 'Gas', 49995.0, 7, 280.0, datetime.date(2020, 5, 27), 'Loan', 50150.0, 300.0, 987654321, 333356789)\n (4, 'Chevrolet', 'Corvette', 2020, 'Sport', 'Gas', 55999.0, 4, 280.0, datetime.date(2020, 5, 27), 'Loan', 58999.0, 300.0, 987444321, 333356789)\n (2, 'Toyota', '4Runner', 2018, 'Sport', 'Gas', 40599.0, 13266, 280.0, datetime.date(2020, 5, 27), 'Loan', 58999.0, 300.0, 987334321, 333356789)"

Any ideas as to what I need to do or add?

Upvotes: 9

Views: 24174

Answers (2)

Adi
Adi

Reputation: 1075

For me, I was exporting my .ipynb file to .pdf, And because I was printing all my knowledge in one print line, it was cropped out in the PDF version.

The easiest solution is to use the Triple Quotes.

# instead of
print("You're Strong, But I Could Snap My Fingers And\nYou'd All Cease To Exist.")

# use
print("""
You're Strong, But I Could Snap My Fingers And 
You'd All Cease To Exist.
"""
[Output]
Youre Strong, But I Could Snap My Fingers And
You'd All Cease To Exist.

Upvotes: 1

BizzyVinci
BizzyVinci

Reputation: 338

When you don't put the output in print statement. "\n" would be printed as "\n" instead of newline in jupyter notebook and python shell.

in: 'A\nB'

out: 'A\nB'

in: print('A\nB')

out:

A
B

The solution you need is: print('\n '.join(str(x) for x in cur.fetchall()))

Upvotes: 18

Related Questions