Parsing user input in Python

17,189

Regular expressions work for me, apply them directly to the value returned by raw_input(). For example:

import re
s1 = '1321 .. 123123'
s2 = '-21323 , 1312321'
s3 = '- 12312.. - 9'

[int(x) for x in re.findall(r'[^,.]+', ''.join(s1.split()))]
=> [1321, 123123]

[int(x) for x in re.findall(r'[^,.]+', ''.join(s2.split()))]
=> [-21323, 1312321]

[int(x) for x in re.findall(r'[^,.]+', ''.join(s3.split()))]
=> [-12312, -9]
Share:
17,189
chamini2
Author by

chamini2

Updated on June 04, 2022

Comments

  • chamini2
    chamini2 almost 2 years

    I need to parse input from the user so it has one of the following formats:

     1321 .. 123123
    

    or

     -21323 , 1312321
    

    A number (can be negative), a comma , or two dots .., and then another number (can be negative).

    Also, the first number must be less or equal <= to the second number.

    If the input fails to have this format, ask again the user for input.

    I have

    def ask_range():
        raw = raw_input()
        raw = raw.strip(' \t\n\r')
        raw = map((lambda x: x.split("..")), raw.split(","))
        raw = list(item for wrd in raw for item in wrd)
        if len(raw) != 2:
            print "\nexpecting a range value, try again."
            return ask_range()
    

    I'm not sure how to get the numbers right.


    EDIT

    The solution I came up with the help from the answers is:

    def ask_range():
        raw = raw_input()
        raw = raw.strip(' \t\n\r')
        raw = re.split(r"\.\.|,", raw)
        if len(raw) != 2:
            print "\nexpecting a range value, try again."
            return ask_range()
    
        left = re.match(r'^\s*-?\s*\d+\s*$', raw[0])
        right = re.match(r'^\s*-?\s*\d+\s*$', raw[1])
        if not (left and right):
            print "\nexpecting a range value, try again."
            return ask_range()
    
        left, right = int(left.group()), int(right.group())
        if left > right:
            print "\nexpecting a range value, try again."
            return ask_range()
    
        return left, right