2

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

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也应该存储在数组中,只是打印不起作用输出应该与它的格式相同。

4

1 回答 1

1

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

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 
于 2019-11-18T12:11:29.320 回答