chamini2
chamini2

Reputation: 2918

Parsing user input in Python

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

Upvotes: 2

Views: 24641

Answers (2)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

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]

Upvotes: 3

rocker_raj
rocker_raj

Reputation: 157

def ask_range():
        raw = raw_input()
        lis = []
        split1 = raw.split("..")
        for i in split1:
            try:
                lis.append(int(i))
            except:
                for j in i.split(","):
                    list.append(int(j))
        if len(raw) != 2:
            print "\nexpecting a range value, try again."
            return ask_range()
        return lis

First split using .. then ,

I think this would help..

Upvotes: 0

Related Questions