Granny Aching
Granny Aching

Reputation: 1435

python displays `\n` instead of breaking a line

I wrote a function to create the VALUES part of a SQL query:

def query_values(data_iterator):
    return ',\n'.join('\n({})\n'.format(',\n'.join('"{}"'.format(value) for value in data_row)
                                     ) for data_row in data_iterator
                      ),

When I call this function and print the result, I get is:

query_values:
('\n("801",\n"printer",\n"barcode printer")\n,\n\n("844",\n"laptop",\n"windows")\n,\n\n("997",\n"printer",\n"barcode printer")\n',)

All in one line. Instead of breaking the line, the \n are displayed.

Originally I had one \n, but then I inserted multiple, just to see if they would get displayed.

The second problem was that there are parentheses around the entire thing, which I didn't want.

I was puzzling over the two issues, and I figured the solution for the second one:

I had a comma at the end of the function. The comma caused the function to return a tuple, instead of a single string.

I removed the comma:

def query_values(data_iterator):
    return ',\n'.join('\n({})\n'.format(',\n'.join('"{}"'.format(value) for value in data_row)
                                     ) for data_row in data_iterator
                      )

and that fixed both problems. The output was now:

query_values:

("801",
"printer",
"barcode printer")
,

("844",
"laptop",
"windows")
,

("997",
"printer",
"barcode printer")

I put the comma back, and the \n were displayed. I removed the comma, and I have multiple lines again.

I have removed extraneous \n, so now I get what I wanted:

query_values:

("801","printer","barcode printer"),
("844","laptop","windows"),
("997","printer","barcode printer")

So, my code works correctly, but I'm totally confused about the \n characters displayed in the old version of the code. Why was that happening?

UPDATE: A couple answers to this question focused on why I was getting a tuple. That's not my question. Why are /n displayed?

Upvotes: 21

Views: 11216

Answers (4)

Granny Aching
Granny Aching

Reputation: 1435

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.

Upvotes: 20

sanooj
sanooj

Reputation: 493

A tuple can be denoted with or without parenthesis, its the comma decides the type.

>>> t = 1, 'a', 'abc'
>>> type(t)
<type 'tuple'>
>>> t
(1, 'a', 'abc')
>>> 

In the above case, you added a trailing comma after the string and python interpreted it as a tuple.

Check this link.

>>> t= 'a',
>>> type(t)
<type 'tuple'>
>>> t
('a',)
>>> t = 'a'
>>> type(t)
<type 'str'>
>>> t
'a'

Upvotes: 0

Nestor Sokil
Nestor Sokil

Reputation: 2272

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. :)

Upvotes: 1

interjay
interjay

Reputation: 110202

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.

Upvotes: 12

Related Questions