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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With