python displays `\n` instead of breaking a line
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 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: xxx
xx
repr: 'xxx\nxx'
---
t : ['xxx\nxx']
element: xxx
xx
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 : xxx
xx
s.__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.