在数字数组中打印字符串

Printing strings in a number array

我正在尝试在矩阵中打印字符串。但我找不到解决方案。

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()

首先它打印出我想要的结果

  0   1   2 
  3   4   5 
  6   7   8
Where to replace ?5

然后就报错了;

TypeError: %d format: a number is required, not str

我该如何解决这个问题。 我希望我的输出像;

  0   1   2 
  3   4   X 
  6   7   8 

X也应该存储在数组中,只是打印不起作用 输出应与原格式相同。

您当前使用的格式字符串要求所有输入均为整数。我已将其更改为在下面的解决方案中使用 f-strings。

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()

输出 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  

输出 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