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.
matrix[position] = "X". From now on, the inserted object is astrtype containing"X". However, in the loop you want to reformat it to%3dwhich is obviously illogical. You cannot reformat the"X"string to a number unless it is a number stored as a string.%s(string) format istead of%d(number). So you must to be working with a string indentation as%3sand not with a number indentation such as%3d. Or better is to use the new method:str.format(). So there will the following source code:print('{0:>3}'.format(.....value....),end='')