sousys sousys - 2 months ago 7
Python Question

How can i easily handle numberseries formated with brackets?

I have a long list of numberseries formated like this:

["4450[0-9]", "6148[0-9][0-9]"]


I want to make a list from one of those series with single numbers:

[44500,44501,..., 44509]


i need to do this for many series within the original list and i'm wondering what the best way is for doing that?

Answer

Probably not the best solution, but you can approach it recursively looking for the [x-y] ranges and generating values (using yield and yield from in this case, hence for Python 3.3+):

import re

pattern = re.compile(r"\[(\d+)-(\d+)\]")

def get_range(s):
    matches = pattern.search(s)
    if not matches:
        yield int(s)
    else:
        start, end = matches.groups()
        for i in range(int(start), int(end) + 1):
            repl = pattern.sub(str(i), s, 1)
            yield from get_range(repl)


for item in get_range("6148[0-9][0-9]"):
    print(item)

Prints:

614800
614801
...
614898
614899