I would like to be able to convert a string such as \"1,2,5-7,10\" to a python list such as [1,2,5,6,7,10]. I looked around and found this, but I was wondering if there is a
Ugh, the answers are so verbose! Here is a short and elegant answer:
def rangeString(commaString):
def hyphenRange(hyphenString):
x = [int(x) for x in hyphenString.split('-')]
return range(x[0], x[-1]+1)
return chain(*[hyphenRange(r) for r in commaString.split(',')])
Demo:
>>> list( f('1,2,5-7,10') )
[1, 2, 5, 6, 7, 10]
Easily modifiable to handle negative numbers or return a list. Also will need from itertools import chain, but you can substitute sum(...,[]) for it if you are not working with range objects (or sum(map(list,iters),[])) and you don't care about being lazy.