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' into a list like [4, 5, 6, 7, 8, 9] in Python. This can be useful for working with ranges specified as strings.
Steps to Convert Numeric String Range to a List
- Split the String: Use the hyphen as a delimiter to split the string.
- Convert to Integers: Convert the split strings to integers.
- Create a Range: Create a range using these integers.
- Convert to List: Convert the range to a list.
Example Program
In this example, we read a string from the user and convert the given numeric string range to a list.
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]
What's Happening Here?
- We split the string
xby the hyphen usingsplit('-'), resulting inaandb. - We convert these split strings to integers using
int(a)andint(b). - We create a range from
atob + 1usingrange(a, b + 1). - Finally, we convert the range to a list using
list(result)and print it.
Reference Tutorials for the Above Program:
- Python List: Learn about list operations and methods.
- Python Range: Understand how to use the
range()function. - Python - Split String: Learn how to split strings in Python.
- Python - Convert String to Integer: Understand how to convert strings to integers.
Try It Yourself: Fun Exercises
- Create Your Own Ranges:
- Take a numeric string range like '10-15' and convert it to a list.
- Dynamic Range Input:
- Use the
input()function to read a numeric string range from the user and convert it to a list.
- Use the
Summary:
In this Python tutorial, we learned how to convert a given numeric string range into a list of numbers using string splitting, integer conversion, range creation, and list conversion. These techniques are useful for manipulating ranges specified as strings. Keep experimenting and have fun with Python!