I have very limited experience with regular expressions so I'm hoping someone can help me out.
I'm making a Python 3 game that has a rectangular grid as the board. I'm trying to make a way for users to enter several board coordinates at once in the following form into a string called coords:
(x1, y1), (x2, y2), (x3, y3), ... (xn, yn)
I want the output to be a list of tuples called cells in a similar form:
[(x1, y1), (x2, y2), (x3, y3), ... (xn, yn)]
So essentially I want to mimic how tuples can be written in Python code.
Right now I am using:
cells = [tuple(coords[i.find('(') + 1: i.rfind(')')].split(',')) for i in coords.split()]
which produces the desired result for inputs in the form (1,2) (3,4) (5,6), with no spaces inside the inputted tuples and spaces between the tuples. However, this breaks for inputs not following exactly that form, and it does nothing to check for valid inputs. For every x- and y-value in the tuples in cells, I need to validate that:
- type(y-value) == type(x-value) == int
- 0 <= y-value < game_board.height
- 0 <= x-value < game_board.width
Ideally, if the users enters multiple valid coordinates and some invalid ones, the valid tuples would be added to cells and the user would be given a message like "The following coordinates were invalid: (x1, y1), ...".
I know I could do this all with a mess of loops and flow control, but is there a more Pythonic way to accomplish this with regex?
Edit: spelling
.strip()on the string get rid of the whitespace that's giving you an issue?spliton spaces though, since I don't know where the user will enter spaces when I give them this flexibility.