在一个单独的文本文件中有一个网格,函数读取该文件并返回一个由网格组成的对象,其中文本文件是逐行读取的
我的问题是,在我的数字坐标中,一位数与两位数的最后一位数不对齐
def load_board(filename):
result = " "
with open(filename) as f:
print(f)
for index, line in enumerate(f):
if index == 0:
result += ' '+' '.join([chr(alphabets + 65) for alphabets in range(len(line) - 1)]) + '\n' #the alphabetical column heading
result += f"{-(index + 1)+(20)}"
if (len(result))<2:
result+=' '.join(result)
for characters in line:
result += " " + (characters)
return result
def save_board(filename, board):
with open(filename, "wt") as f:
f.write(board)
b = load_board("l19.txt")
print(b)
save_board("l19b.txt", b)
这会产生一个输出
A B C D E F G H I J K L M N O P Q R S
19 . . . . @ @ @ . O O . . @ . O O O . O
18 @ O O @ O @ . . @ O @ O . . . @ @ . @
17 @ O . . @ O . O O O O O . O O O O O @
16 . . @ @ . O O . @ . . O @ O . @ . O .
15 O . @ . @ . O @ . O O @ @ O . . O @ O
14 O . . . O O O @ . @ @ . . . @ . O @ @
13 . . @ O @ . . @ . . O O O . @ . @ . .
12 . . @ @ . @ @ @ . . . @ O . O . . . @
11 @ O . . @ . @ @ @ @ O . . @ O O O @ O
10 @ . . O . @ @ O @ O O @ @ . @ . O @ .
9 @ O O O . . @ O . . @ @ O @ @ @ . O O
8 @ @ O @ . O O O . @ . O @ . @ @ @ . @
7 @ . O . O @ O O . O O . @ O @ . . @ O
6 @ . . . O @ @ O O @ . @ @ . . O . O .
5 O O @ @ . . O @ @ . @ . @ . O @ @ O .
4 @ . O . . O O . @ O @ O @ O O . @ @ .
3 @ @ O O @ . O . @ . O @ . @ O @ O . .
2 . . . O O @ @ O . @ O . O . @ O O @ .
1 @ @ . @ O . @ @ . . @ O O O O O @ @ @
我试图通过添加条件语句来对齐它,条件语句声明如果数字的长度小于2,则添加一个空格,但它不起作用
1条答案
按热度按时间lf5gs5x21#
使用f-string的选项将其格式化为长度为2的值,这样就可以删除无用的
if (len(result))<2:
块您还可以使用
string.ascii_uppercase
进行简化