New line being printed as “n” instead of actual new line
New line being printed as “n” instead of actual new line
I'm trying to print a simple game board.
places = [" "] * 9
board = (places[8] + "|" + places[7] + "|" + places[6] + "n",
places[5] + "|" + places[4] + "|" + places[3] + "n",
places[2] + "|" + places[1] + "|" + places[0] + "n")
print(board)
But instead of a board I get this:
(' | | n', ' | | n', ' | | n')
I want to print it without the parentheses and with new lines instead of n. How can I do this?
print(''.join(board))
Why did you make a tuple in the first place?
– user2357112
Aug 22 at 18:05
@user2357112 I'm new to programming and don't know what a tuple is. This just made sense to me.
– Adam Grey
Aug 22 at 18:08
4 Answers
4
Don't print whole tuple, but it's elements, e.g.:
for i in board:
print(i)
You just have to use this line to print:
print(*board,sep="")
Explanation: the operator * is the unpacking operator: the tuple board
is then unpacked, and it is like you've done:
board
print( places[8] + "|" + places[7] + "|" + places[6] + "n",
places[5] + "|" + places[4] + "|" + places[3] + "n",
places[2] + "|" + places[1] + "|" + places[0] + "n",
sep="")
Because you've put commas on the end of each line in the brackets, you've made a tuple, which is an iterable, like a list. Just replace the commas with a + at the start of the next line
board = ('line 1' + 'n'
+ 'line 2' + 'n'
+ 'line 3' + 'n')
This creates a string instead of a tuple.
places = [" "] * 9
print(places[8] + "|" + places[7] + "|" + places[6] + "n" + places[5] + "|" +
places[4] + "|" + places[3] + "n" + places[2] + "|" + places[1] + "|" + places[0] +
"n")
This is what you're looking for.
The problem was that "n" only works in print statements.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Yo. Board is a tuple, that's how it's going to print. You could do
print(''.join(board))
.– David Zemens
Aug 22 at 18:00