Parsing numeric ranges

Corey Richardson kb1pkl at
Fri Feb 25 10:36:32 CET 2011

On 02/25/2011 04:27 AM, Seldon wrote:
> Hi all,
> I have to convert integer ranges expressed in a popular "compact" 
> notation (e.g. 2, 5-7, 20-22, 41) to a the actual set of numbers (i.e. 
> 2,5,7,20,21,22,41).
> Is there any library for doing such kind of things or I have to write it 
> from scratch ?
> Thanks in advance for any answers.
> Seldon

I don't know of any library, but range() in Python 2 or list(range()) in
python 3 should provide the brunt force of what you're trying to do.

for example,

final_nums = [2]
compact_range = "5-7".split('-')
final_nums += range(int(compact_range[0]), int(compact_range[1]) + 1)

And then looping through your compact notation deciding when it's a
range notation and when it's a literal is all you have to do.

Corey Richardson

More information about the Python-list mailing list