JJ98
JJ98

Reputation: 11

Checking if string is in a specific form in Python

I need to check if an input string is in this specific form x,y because I need these coordinates. I got this as my input-question:

x, y = input("Place wall in x,y give q to quit : ").split(",")

but how do I check if the user actually gives it in the form x,y?

Upvotes: 1

Views: 1020

Answers (4)

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

Unpacking will throw ValueError if your string is not in the right format (does not have comma, has too many commas...) because array after split() method will be the wrong size. So you can catch it.

try:
    x, y = input("Place wall in x,y give q to quit : ").split(",")
except ValueError:
    print("Unexpected input")

Upvotes: 1

Curtis Mattoon
Curtis Mattoon

Reputation: 4742

Another answer, just because.

def check_input(s):
    if s.strip() in ['q', 'Q']:
        raise SystemExit("Goodbye!")

    try:
        x, y = s.split(',')

        # Or whatever specific validation you want here
        if int(x) < 0: raise AssertionError
        if int(y) < 0: raise AssertionError

        return True
    except (ValueError, AssertionError):
        return False

print(check_input("1,3")) # True
print(check_input("foo")) # False

Upvotes: 0

Ethan McCue
Ethan McCue

Reputation: 998

You can use regular expressions https://docs.python.org/3.5/library/re.html as a general solution for pattern matching.

You can also just put the data conversions you need to do in a try except block like this

try:
    handle_input()
except Exception as e:
    print ("input not correct")

Upvotes: 1

Iluvatar
Iluvatar

Reputation: 1537

import re
p = re.compile("^\d+,\d+$");
while True:
    string = input("Place wall in x,y give q to quit : ")
    if p.match(string):
        break

You can then get the values from string as before.

Upvotes: 2

Related Questions