2

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
chamini2
  • 2,820
  • 2
  • 24
  • 37
  • 1
    Check out this [relevant thread](http://stackoverflow.com/questions/4289331/python-extract-numbers-of-a-string). Most people will say use regex, but if the numbers are always integers, there are simpler ways. – wflynny Jun 26 '13 at 16:16

2 Answers2

3

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]
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0
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..

rocker_raj
  • 159
  • 12