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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With