Open In App

Python | Convert String ranges to list

Sometimes, while working in applications we can have a problem in which we are given a naive string that provides ranges separated by a hyphen and other numbers separated by commas. This problem can occur across many places. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using sum() + split() + list comprehension + enumerate() The combination of above functions can be used to perform these tasks. In this, the split is performed on hyphens and comma and accordingly range, numbers are extracted and compiled into a list. 






# Python3 code to demonstrate working of
# Convert String ranges to list
# Using sum() + list comprehension + enumerate() + split()
 
# initializing string
test_str = "1, 4-6, 8-10, 11"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert String ranges to list
# Using sum() + list comprehension + enumerate() + split()
res = sum(((list(range(*[int(b) + c
           for c, b in enumerate(a.split('-'))]))
           if '-' in a else [int(a)]) for a in test_str.split(', ')), [])
 
# printing result
print("List after conversion from string : " + str(res))

Output : 
The original string is : 1, 4-6, 8-10, 11
List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]

Time complexity: O(n), where n is the number of items in the input string ‘test_str’ (number of elements in the list after the conversion)
Auxiliary space: O(n), where n is the number of items in the input string ‘test_str’ (number of elements in the list after the conversion).



Method #2 : Using map() + split() + lambda This task can also be performed using above functions. Similar to method above. The only difference is that we use map() and lambda function to reduce complex readability. Works only with Python2. 




# Python2 code to demonstrate working of
# Convert String ranges to list
# Using map() + lambda + split()
 
# initializing string
test_str = "1, 4-6, 8-10, 11"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert String ranges to list
# Using map() + lambda + split()
temp = [(lambda sub: range(sub[0], sub[-1] + 1))(map(int, ele.split('-')))\
        for ele in test_str.split(', ')]
 
res = [b for a in temp for b in a]
 
# printing result
print("List after conversion from string : " + str(res))

Output : 
The original string is : 1, 4-6, 8-10, 11
List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]

Method #3: Using re

This method uses the regular expression library in Python to extract the ranges and single values from the string and create the final list.




import re
 
test_str = "1, 4-6, 8-10, 11"
 
print("The original string is : " + test_str)
res=[]
#Extracting the ranges and single values from the string
for i in test_str.split(","):
    if re.search(r'\d+-\d+', i):
        #Creating the final list
        res.extend(range(int(i.split('-')[0]), int(i.split('-')[1])+1))
    else:
        res.append(int(i))
# printing result
print("List after conversion from string : " + str(res))

Output
The original string is : 1, 4-6, 8-10, 11
List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]

Time Complexity: O(n)
Auxiliary Space: O(n) 

Method #4: Using split(),find() methods and for loops




# Python3 code to demonstrate working of
# Convert String ranges to list
 
# initializing string
test_str = "1,4-6,8-10,11"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert String ranges to list
x=test_str.split(",")
y=[]
for i in x:
    if i.find("-")!=-1:
        a,b=i.split("-")
        for j in range(int(a),int(b)+1):
            y.append(j)
    else:
        y.append(int(i))
# printing result
print("List after conversion from string : " + str(y))

Output
The original string is : 1,4-6,8-10,11
List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]

Time Complexity : O(N)
Auxiliary Space : O(N)

Method #5: Using a for loop and string manipulation.

Step-by-step approach:




# initializing string
test_str = "1, 4-6, 8-10, 11"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert String ranges to list
# Using for loop and string manipulation
res = []
for s in test_str.split(', '):
    if '-' in s:
        start, end = map(int, s.split('-'))
        res.append(start)
        for i in range(start+1, end+1):
            res.append(i)
    else:
        res.append(int(s))
 
# printing result
print("List after conversion from string : " + str(res))

Output
The original string is : 1, 4-6, 8-10, 11
List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]

Time complexity: O(n^2) – the nested for loops in the list comprehension contribute to this time complexity.
Auxiliary space: O(n) – we create a list to store the output, which has a length of n.

Method #6: Using the itertools module

Step-by-step approach:




import itertools
 
# initializing string
test_str = "1, 4-6, 8-10, 11"
 
# printing original string
print("The original string is : " + test_str)
 
# Convert String ranges to list
# Using the itertools module
res = []
ranges = test_str.split(", ")
for r in ranges:
    if "-" not in r:
        res.append(int(r))
    else:
        start, end = map(int, r.split("-"))
        res.extend(range(start, end+1))
 
# printing result
print("List after conversion from string : " + str(list(res)))

Output
The original string is : 1, 4-6, 8-10, 11
List after conversion from string : [1, 4, 5, 6, 8, 9, 10, 11]

Time complexity: O(n)
Auxiliary space: O(n)


Article Tags :