I have "2,5,7-9,12"
string.
I want to get [2, 5, 7, 8, 9, 12] list from it.
Is there any built-in function for it in python?
Thanks.
UPD. I suppose, the straight answer is No. Anyway, thanks for your "snippets". Using one, suggested by Sven Marnach.
s = "2,5,7-9,12"
ranges = (x.split("-") for x in s.split(","))
print [i for r in ranges for i in range(int(r[0]), int(r[-1]) + 1)]
prints
[2, 5, 7, 8, 9, 12]
s = "2,5,7-9,12"
result = list()
for item in s.split(','):
if '-' in item:
x,y = item.split('-')
result.extend(range(int(x), int(y)+1))
else:
result.append(int(item))
print result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With