Convert numeric string range to a list
What You'll Learn: In this tutorial, you'll discover how to convert a numeric string range like '4-9' to a list like [4, 5, 6, 7, 8, 9] in Python. This involves splitting the string, converting the parts to integers, creating a range, and then converting that range to a list.
Steps to Convert Numeric String Range to a List
- Split the String:
- Use a hyphen as the delimiter to split the string.
- Convert to Integers:
- Convert the resulting string parts into integers.
- Create a Range:
- Use these integers to create a range object.
- Convert to List:
- Finally, convert the range object to a list using the
list()function.
- Finally, convert the range object to a list using the
Example Program
This program reads a string from the user, converts the given numeric string range to a list, and prints the result.
Example Code:
python
# Take a numeric string range
x = '4-9'
# Split the string by hyphen
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, 5, 6, 7, 8, 9]
Try It Yourself: Fun Exercises
- Convert Different Ranges:
- Change the input string to different ranges like '1-5' or '10-20' and see the resulting list.
- User Input:
- Modify the program to read the numeric string range from the user and convert it to a list.
Summary:
In this Python tutorial, we learned how to convert a given numeric string range into a list of numbers. This involves splitting the string, converting to integers, creating a range, and converting the range to a list. Keep experimenting and have fun with Python!