I have to create a function to separate the user entered coordinates of a chessboard, they will consist of a letter and nummbers from 0 to 26, in a format like this
a10
h21
r20 and so on
and it has to return a tuple
below you have my code which does not have the correct outoput, the reason I am writing this it is becuase I do not understand which would be the best approach, do I need to use regex or there is another approach with just split? The code below returns an empty space in the list, which is not ideal, also it is not a tuple with integers... any suggestions?
import re
loc ="a10"
def location2index(loc:str) -> tuple[int, int]:
'''converts chess location to corresponding x and y coordinates'''
mycoord_tuple = re.split('(\d+)', loc)
return (mycoord_tuple)
If you are sure that first character is always an alphabet(single place only), then no need to use regex, just split and return the desired result.
loc = 'a10'
print(loc[0], loc[1:])
And to have method to reverse-map, with reference to answer by @PCM,
def reverse_map(location):
alphabet = chr(96+int(location[0])) # return a for 1, b for 2 so on.
number = location[1]
return f'{alphabet}{number}'
output = location2index('a10') # (1,10)
reverse_mapping = reverse_map(output)
print(reverse_mapping) # a10
Split the string without regex (The first element is gonna be a letter, and the rest is gonna be numbers), and apply ord
function to convert the letter to the corresponding number -
def location2index(loc:str) -> tuple[int, int]:
'''converts chess location to corresponding x and y coordinates'''
x = ord(loc[0]) - 96 # Transforms to a number - a = 1, b = 2, c =3 ...
y = int(loc[1:])
return (x,y)
loc ="a10"
output = location2index(loc)
print(output) # (1,10)
Also, check this
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.