maurobio maurobio - 1 year ago 99
Python Question

Python - Create set from string

I have strings in the format

"1-3 6:10-11 7-9"
and from them I want to create number sets as follows

For creating the set from the range of numbers, I have the following code:

def create_set(src):
lset = []
if len(src) > 0:
pos = src.find('-')
if pos != -1:
first = int(src[:pos])
last = int(src[pos+1:])
return [int(src)] # Only one number
for j in range (first, last+1):
return set(lset)

But I cannot figure out how to correctly treat the ':' when it appears in the string. Can someone help me?

Thanks in advance!

EDIT: By the way, is there a more compact way of parsing such strings, perhaps using regular expressions?

xnx xnx
Answer Source

Something like this might work for you:

s = '1-3 6:10-11 7-9'
s = s.replace(':', ' ')
lset = set()
fs = s.split()
for f in fs:
    r = f.split('-')
    if len(r)==1:
        # add a single number
        # add a range of numbers (inclusive of the endpoints)
        lset |= set(range(int(r[0]), int(r[1])+1))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download