简体   繁体   中英

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM