Skip to content Skip to sidebar Skip to footer

Expand Certain Substrings Elegantly Inside A Larger String In Python

Hi I want to elegantly expand the substring of the type 4-6 to 4,5,6 in a larger string like s = '235:2,4,6-9,12,14-19;240:3,5-9,10;245:4,9,10-15,18' print expand(s) 235:2,4,6,7,8

Solution 1:

You can do:

>>>import re>>>defrepl(match):...    start, end = match.groups()...return','.join(str(i) for i inrange(int(start), int(end)+1))...>>>re.sub(r'(\d+)-(\d+)', repl, "235:2,4,6-9,12,14-19;240:3,5-9,10;245:4,9,10-15,18")
'235:2,4,6,7,8,9,12,14,15,16,17,18,19;240:3,5,6,7,8,9,10;245:4,9,10,11,12,13,14,15,18'

This uses the fact that the repl argument to re.sub can be a callable that takes as argument the match and returns the replacing string.

The expand(s) function would then be:

import re

defrepl(match):
    start, end = match.groups()
    return','.join(str(i) for i inrange(int(start), int(end)+1))

defexpand(s):
    return re.sub('(\d+)-(\d+)', repl, s)

Post a Comment for "Expand Certain Substrings Elegantly Inside A Larger String In Python"