python 如何使数字坐标列最后一位的两位数与个位数一致

l0oc07j2  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(162)

在一个单独的文本文件中有一个网格,函数读取该文件并返回一个由网格组成的对象,其中文本文件是逐行读取的
我的问题是,在我的数字坐标中,一位数与两位数的最后一位数不对齐

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,则添加一个空格,但它不起作用

lf5gs5x2

lf5gs5x21#

使用f-string的选项将其格式化为长度为2的值,这样就可以删除无用的if (len(result))<2:
您还可以使用string.ascii_uppercase进行简化

from string import ascii_uppercase

def load_board(filename):
    result = "  "
    with open(filename) as f:
        for index, line in enumerate(f):
            # the alphabetical column heading
            if index == 0:
                result += ' ' + ' '.join(ascii_uppercase[:len(line) - 1]) + '\n'
            # the number prefix
            result += f"{19 - index:2d}"
            # the chars
            result += ' ' + ' '.join(line.strip()) + '\n'
    return result

相关问题