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
This might be an overkill, but I just like pyparsing:
from pyparsing import *
def return_range(strg, loc, toks):
if len(toks)==1:
return int(toks[0])
else:
return range(int(toks[0]), int(toks[1])+1)
def parsestring(s):
expr = Forward()
term = (Word(nums) + Optional(Literal('-').suppress() + Word(nums))).setParseAction(return_range)
expr << term + Optional(Literal(',').suppress() + expr)
return expr.parseString(s, parseAll=True)
if __name__=='__main__':
print parsestring('1,2,5-7,10')