Alex Rivera | Logout

How to convert numeric string ranges to a list in Python

Asked 2011-06-19T21:28:28.467
28

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 clean and simple way to do this in Python.

Edit
Report

1 Answer

4

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')
answered 2011-06-19T22:24:38.493

Your Answer