maurobio maurobio - 3 months ago 10
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
{1,2,3,6,10,11,7,8,9}
.

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:])
else:
return [int(src)] # Only one number
for j in range (first, last+1):
lset.append(j)
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

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
        lset.add(int(r[0]))
    else:
        # add a range of numbers (inclusive of the endpoints)
        lset |= set(range(int(r[0]), int(r[1])+1))
print(lset)
Comments