Python Newline n not working in jupyter notebooks

Question:

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?

Asked By: javaluv21

||

Answers:

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: 'AnB'

out: 'AnB'

in: print('AnB')

out:

A
B

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

Answered By: BizzyVinci

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 AndnYou'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.
Answered By: Aditya Rajgor
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.