Jean Swanborn
Jean Swanborn

Reputation: 13

How to read user input containing coordinates in parenthesis

I am making a really simple game where you make a table of numbers and hide a bomb that the user needs to find.

Here is the code:

import random
def game(rows, colums):   
    table = (rows * colums - 1) * [' '] + ['bomb']    
    random.shuffle(table)    
    while True:    
        position = input('Enter next position (x, y):')    
        bombposition = position.split()    
        if table[int(bombposition[0])*colums + int(bombposition[1])] == 'bomb':    
            print('you found the bomb!')    
            break    
        else:    
            print('no bomb at', position) 

the error:

game(1,0)    
Enter next position (x, y):>?    
(1,0)    
Traceback (most recent call last):    
  File "input", line 1, in <module>   
  File "input", line 8, in game    
ValueError: invalid literal for int() with base 10: '(1,0)' 

Upvotes: 1

Views: 811

Answers (2)

Riccardo Bucco
Riccardo Bucco

Reputation: 15374

You just need to change the way you compute bombposition:

bombposition = position.lstrip("(").rstrip(")").split(",")

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117926

Firstly split uses whitespace by default, so to split on a comma you'd need position.split(','). Although even then, your split will still have the ( and ) attached to your strings if you split on , for example in your case '(1' and '0)'. I'd suggest maybe using a regex to extract the numbers from your input

import re

position = input('Enter next position (x, y):') 
match = re.match(r'\((\d+)\, *(\d+)\)', position)
if match:
    x = int(match.group(1))
    y = int(match.group(2))
else:
    # input didn't match desired format of (x, y)

Upvotes: 1

Related Questions