0

I want to create pyqt widget like in MS Office or OOo print dialogs, that allows to input sets of ranges like "1, 3-4, 7-9". Does python have built-in tool or third party package for converting such strings into lists? For example:

"1, 3-4, 7-9" => [1,3,4,7,8,9]

ps: How this widget called?

2 Answers 2

1

Not sure if there's a built-in or a third party package available for this, but something like this should do it:

from itertools import chain
def my_range(*args):
    args = map(int,args)                                                               
    if len(args) == 1:
        return args
    return range(args[0], args[1]+1)

def func(strs):
    return list(chain.from_iterable(my_range(*x.split('-')) for x in strs.split(', ')))
strs = "1, 3-4, 7-9"
print func(strs)
#[1, 3, 4, 7, 8, 9]
1
  • Thank you, your solution works, but only with position numbers
    – zhulik
    Commented Jun 5, 2013 at 9:48
0

Made my own version without itertools.

def expander(inpt):
    ret = []
    for token in inpt.split(','):
        if '-' in token:
            a, b = token.strip().split('-')
            ret.extend(range(int(a), int(b)+1))
        else:
            ret.append(int(token))
    return ret

print(expander('1, 3-4, 7-9'))

Keep in mind it would be healthy to check this string with regex.

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.