python displays `\n` instead of breaking a line
It seems that this is the behavior of tuples. When a tuple is printed, print calls __repr()__
on each element. The same is also true for lists.
I tried this:
tup = "xxx\nxx",lst =["xxx\nxx"]for t in tup,lst: print('t :', t) for s in t: print('element:',s) print(' repr:',s.__repr__()) print('---')
and the output is:
t : ('xxx\nxx',)element: xxxxx repr: 'xxx\nxx'---t : ['xxx\nxx']element: xxxxx repr: 'xxx\nxx'---
So, the same behavior for both tuples and lists.
When we have a string, calling __repr__()
doesn't expand \n
characters, and puts quotes around it:
s = "xxx\nxx"print('s :', s)print('s.__repr__():', s.__repr__())
outputs:
s : xxxxxs.__repr__(): 'xxx\nxx'
This tuple behavior was mentioned in comments by running.t, interjay and Daniel Roseman, but not in answers, that's why I'm posting this answer.
Writing return something,
is the same as return (something,)
: It returns a tuple containing one element. When you print
this, it will show the outer parentheses for the tuple, and the string inside will be printed as its source code representation, i.e. with escape codes and inside quotes.
However, return something
simply returns that value, which can then be printed normally.
It seems that's the behavior for tuples in Python.You can test this with a simpler case like so:
>>> print ("xxx\n\nx",)('xxx\n\nx',)
Seems like Python helps you with debugging and escapes all the command sequences in strings when printing, so that strings appear the same way they were defined.
It did confuse you though, funny case. :)