Created
April 25, 2012 17:54
-
-
Save kgaughan/2491663 to your computer and use it in GitHub Desktop.
Parsing a comma-separated list of numbers and range specifications in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import chain | |
def parse_range(rng): | |
parts = rng.split('-') | |
if 1 > len(parts) > 2: | |
raise ValueError("Bad range: '%s'" % (rng,)) | |
parts = [int(i) for i in parts] | |
start = parts[0] | |
end = start if len(parts) == 1 else parts[1] | |
if start > end: | |
end, start = start, end | |
return range(start, end + 1) | |
def parse_range_list(rngs): | |
return sorted(set(chain(*[parse_range(rng) for rng in rngs.split(',')]))) |
In [8]: def status_code(v):
...: if '*' == v:
...: return list(range(200, 300))
...: rv = []
...: sp = v.split(',')
...: for x in sp:
...: if '-' in x:
...: start, stop = map(int, x.split('-'))
...: rv += range(start, stop + 1)
...: else:
...: rv += [int(x)]
...: return rv
...
In [12]: status_code('200-204,206,301,302,400-404,500')
Out[12]: [200, 201, 202, 203, 204, 206, 301, 302, 400, 401, 402, 403, 404, 500]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sjaek
danke!