Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
Granny Aching Avatar asked Mar 19 '19 14:03

Granny Aching


People also ask

Why is Python printing \n?

This occurs because, according to the Python Documentation: The default value of the end parameter of the built-in print function is \n , so a new line character is appended to the string.

What does '\ n do in Python?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.

How do you get rid of N in Python?

Method 2: Use the strip() Function to Remove a Newline Character From the String in Python. The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string.

How do you break a line in Python?

To break a line in Python, use the parentheses or explicit backslash(/). Using parentheses, you can write over multiple lines. The preferred way of wrapping long lines is using Python's implied line continuation inside parentheses, brackets, and braces.


1 Answers

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.

like image 137
Granny Aching Avatar answered Sep 30 '22 17:09

Granny Aching