Python | Convert string ranges to list



Method # 1: Using sum () + split () + list comprehension + enumerate()
Combination of the above functions can be used to accomplish these tasks. In this case, the splitting is performed by hyphen and comma and, accordingly, the range, the numbers are extracted and compiled into a list.

# Python3 code to demonstrate how it works
# Convert string ranges to a list
# Using sum () + list comprehension + enumerate () + split ()

 
# initialization string

test_str = "1, 4-6, 8-10, 11"

 
# print original line

print ( "The original string is:" + test_str)

  
# Convert string ranges to a list
# Using sum () + list comprehension + enumerate () + split ()

res = sum ((( list ( range ( * [ int (b) +

for c, b in enumerate (a.split ( `-` ))]))

  if ` -` in a else [ int (a)]) for a in test_str.split ( `, ` )), [ ])

 
# print 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] 

< p> Method # 2: Using map () + split () + lambda
This task can also be done using the above functions. Similar to the method above. The only difference is that we use map () functions and lambda expressions to reduce complex readability. Only works with Python2.

# Python2 code to demonstrate how it works
# Convert string ranges to list
# Using map () + lambda + split ()

 
# initialization string

test_str = "1, 4-6, 8-10, 11"

 
# printing the original line

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]

  
# print result

print ( "List after conversion from string:" + str (res))

Exit:

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