there's a grid in a seperate text file and the function reads this file and returns an object consisting of the grid where the text file is read line by line
my issue is that in my numerical coordinates the single digit doesn't align with the last digit of the double digit numbers
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)
this gives me an output of
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 @ @ @
i tried to get it aligned by adding a conditional statement stating that if the length of the number is less than 2 to add a space however it didn't work
Use the options of f-string to format as a 2 length value, so you can remove the useless if (len(result))<2:
block
You can also simplify using 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.