Reputation: 27
I'm trying to print strings in a matrix. But I couldn't find a solution for that.
game_size = 3
matrix = list(range(game_size ** 2))
def board():
for i in range(game_size):
for j in range(game_size):
print('%3d' % matrix[i * game_size + j], end=" ")
print()
board()
position = int(input("Where to replace ?"))
matrix[position] = "X"
board()
First it prints this as exactly what I want
0 1 2
3 4 5
6 7 8
Where to replace ?5
Then It came up with an error;
TypeError: %d format: a number is required, not str
How can I solve this problem. I want my output like;
0 1 2
3 4 X
6 7 8
Also X should be stored in array, just printing that doesn't work Output should be same format as it is.
Upvotes: 1
Views: 814
Reputation: 14516
You are currently using a format string which requires that all the inputs are integers. I've changed this to using f-strings in the solution below.
game_size = 3
matrix = list(range(game_size ** 2))
def board():
for i in range(game_size):
for j in range(game_size):
print(f'{matrix[i * game_size + j]}'.rjust(3), end=" ")
print()
board()
position = int(input("Where to replace ?"))
matrix[position] = "X"
board()
Output with game_size=3
:
0 1 2
3 4 5
6 7 8
Where to replace ?5
0 1 2
3 4 X
6 7 8
Output with game_size=5
:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
Where to replace ?4
0 1 2 3 X
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
Upvotes: 1