Convert Numeric String Range to a List
Python - Convert Numeric String Range to a List
To convert numeric string range like '4-9'
to a list like [4, 5, 6, 7, 8, 9]
in Python: split the string using hyphen as delimiter, convert the splits to integers, create a range using these integers, and then convert the range to a list.
Program
In the following program, we read a string from user using input() function, and convert the given numeric string range to a list.
Python Program
# Take a numeric string range
x = '4-9'
# Split the string by hypehn
a, b = x.split('-')
# Convert string splits into integers
a, b = int(a), int(b)
# Create a range from the given values
result = range(a, b + 1)
# Convert the range into list
result = list(result)
print(result)
Output
4-9
[4, 5, 6, 7, 8, 9]
Reference tutorials for the above program
Summary
In this Python Tutorial, we learned how to convert a given numeric string range into a list of numbers.