【问题标题】:Printing strings in a number array在数字数组中打印字符串
【发布时间】:2020-03-13 19:19:40
【问题描述】:

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

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 也应该存储在数组中,只是打印不起作用 输出的格式应该和原来的一样。

【问题讨论】:

  • 使用 %s 而不是 %d
  • 问题在这里:matrix[position] = "X"。从现在开始,插入的对象是一个包含"X"str 类型。但是,在循环中,您想将其重新格式化为%3d,这显然是不合逻辑的。您不能将 "X" 字符串重新格式化为数字,除非它是存储为字符串的数字。
  • 您认为是否有解决方案。我想也许它可以用 if 语句解决。但我做不到。
  • 是的,当然@Ahmeed_Hawary 已经回答了你。使用%s(字符串)格式而不是%d(数字)。因此,您必须使用字符串缩进为%3s,而不是使用数字缩进,例如%3d。或者更好的是使用新方法:str.format()。所以会有如下源码:print('{0:>3}'.format(.....value....),end='')

标签: python arrays list for-loop list-manipulation


【解决方案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 

【讨论】:

  • 这对我不起作用,因为我希望它采用那种格式,数字之间应该有差距
  • 您可以在格式字符串中添加更多空格。我已经更新了示例。
  • 其实这不是动态的。如果我给游戏大小 5,最后 3 行打滑 :(
  • 我再次更新它,使用str.rjust。这符合您的标准吗?
  • 顺便说一句,这种方法.rjust() 不是必需的!您可以改用以下语法:print(f'{matrix[ i * game_size + j ]:>3}', end='')
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 2021-07-24
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 2021-09-29
相关资源
最近更新 更多