Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping "\n" new line in list comprehension vs for loop in Python

Escaping "\n" new line in list comprehension in Python

for loop

string_grid = ''
for i in self.board:
    string_grid += "\n" + str(i)
return string_grid

Returns:

[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

But how come the list comprehension:

return str(["\n" + str(col) for col in self.board])


returns this:

['\n[0, 0, 0, 0, 0]', '\n[0, 0, 0, 0, 0]', '\n[0, 0, 0, 0, 0]', '\n[0, 0, 0, 0, 0]', '\n[0, 0, 0, 0, 0]']

I have been trying to make it work for a long time but no matter what I do, the new-line is not being escaped in the stdout.

like image 922
Clever Programmer Avatar asked Sep 12 '15 12:09

Clever Programmer


2 Answers

In the first example, you create a string, in the second a list.

You have to join the list to a string:

return ''.join("\n{0}".format(col) for col in self.board)
like image 89
Daniel Avatar answered Oct 14 '22 11:10

Daniel


This might help you:

board = [[0] * 5] * 5       # Produce an empty board
print board                 # Display the board as a list of lists

print("\n".join([str(row) for row in board]))

For each row, convert the list of board numbers into a textual representation. Use the join function to join each row in the resulting list with a newline. Giving the following output:

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

Replace print() with return

like image 29
Martin Evans Avatar answered Oct 14 '22 10:10

Martin Evans