How to convert numeric string ranges to a list in Python

Viewed 13004

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.

8 Answers

From here: https://gist.github.com/raczben/76cd1229504d82115e6427e00cf4742c

def number(a, just_try=False):
    """
    Parse any representation of number from string.
    """
    try:
        # First, we try to convert to integer.
        # (Note, that all integer can be interpreted as float and hex number.)
        return int(a)
    except:
        # The order of the following convertions doesn't matter.
        # The integer convertion has failed because `a` contains hex digits [x,a-f] or a decimal
        # point ['.'], but not both.
        try:
            return int(a, 16)
        except:
            try:
                return float(a)
            except:
                if just_try:
                    return a
                else:
                    raise


def str2numlist(s):
    """
    Convert a string parameter to iterable object.
    """
    return [y for x in s.split(',') for y in str_ranges_to_list(x) ]


def str_ranges_to_list(s):
    """
    Convert a string parameter to iterable object.
    """
    s = s.strip()
    try:
        begin,end=s.split(':')
        return range(number(begin), number(end))
    except ValueError: # not enough values to unpack
        return [number(s)]

Initializing string

test_str = "1, 4-6, 8-10, 11"

printing original string

print("The original string is : " + test_str)

Convert String ranges to list

res = sum(((list(range(*[int(b) + c 
           for c, b in enumerate(a.split('-'))]))
           if '-' in a else [int(a)]) for a in test_str.split(', ')), [])

printing result

print("List after conversion from string : " + str(res))
Related