Open In App

Python | Convert String ranges to list

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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. 

Python




# 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.

Python3




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




# 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:

  • Initialize an empty list res.
  • Split the input string test_str using , as the delimiter and iterate through each element in the resulting list using a for loop.
  • For each element, check if it contains a ‘-‘ character using the in operator.
  • If it does, split the element using ‘-‘ as the delimiter to obtain the start and end values of the range.
  • Convert both start and end values to integers using the int() function.
  • Append the start value to the res list.
  • Iterate through the range of numbers from start+1 to end using a for loop, and append each number to the res list.
  • If the element does not contain a ‘-‘ character, convert it to an integer using the int() function and append it to the res list.
  • Print the res list.

Python3




# 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 the itertools module.
  • Split the input string into a list of strings, where each string represents either a single integer or a range of integers.
  • Use a for loop to iterate over the list of strings.
  • If a string represents a single integer, convert it to an integer and append it to the result list.
  • If a string represents a range of integers, convert it to a tuple of two integers, representing the start and end of the range.
  • Use the itertools.chain() method to concatenate the range of integers generated by the range() method for each tuple in the list.
  • Convert the concatenated iterator to a list.
  • Print the final list.

Python3




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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads