Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand a string describing a set of numbers noted as a list of numbers and/or ranges [closed]

Tags:

python

regex

I need to parse a string which describes a set of numbers. The numbers are listed in order, but a range of consecutive numbers can be abbreviated with a "range" using a hyphen/dash.

Example: "001,008-011,020"

I want to interpret this string this as an ordered list: [ 1, 8, 9, 10, 11, 20 ]

There could be a arbitrary number of ranges and elements.

like image 561
dannedanne Avatar asked Dec 08 '22 10:12

dannedanne


2 Answers

You could do something like the following..

>>> def findval(str):
...     val = []
...     for x in str.split(','):
...         if '-' in x:
...            lnum, rnum = x.split('-')
...            lnum, rnum = int(lnum), int(rnum)
...            val.extend(range(lnum, rnum + 1))
...         else:
...            lnum = int(x)
...            val.append(lnum)
...     return val

>>> findval('001,008-011,020')
[1, 8, 9, 10, 11, 20]

See Working demo

like image 124
hwnd Avatar answered Apr 06 '23 00:04

hwnd


If you know that the string will always be in that format...

x =  "001,008-011,020"

x = x.split(',') # Split at the commas

y = []

# Iterate over the list
for i in x:
    try:
        # Will append the integer to your output list
        y.append(int(i))
    except ValueError:
        # If you get a ValueError (from trying to int('008-011') for example)
        # then split the string at the hyphen and individually append
        # the integers in between.
        j = i.split('-')
        for k in range(int(j[0]), int(j[1])+1):
            y.append(k)

I think that should work, though you may want to check that no other ValueErrors will be inadvertantly caught in the try/except loop.

like image 45
Ffisegydd Avatar answered Apr 05 '23 23:04

Ffisegydd