1

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?

4 Answers 4

2
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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")

Comments

1

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")

Comments

0

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

2 Comments

You should not depend on assert for input validation. Python does not guarantee that they will run. And when -O is given they are not. Use if x: raise AssertionError instead if you must.
Interesting, I didn't know that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.