1

I would like to convert a string into an integer list using python. Some examples might be:

"1-4, 7, 9-11" into [1,2,3,4,7,9,10,11]
"5-9" into [5,6,7,8,9]
"1,2,3,10,11" into [1,2,3,10,11]
"1-3,5,6,7" into [1,2,3,5,6,7]

Is there a quick and easy way to do this?

Georgy
  • 12,464
  • 7
  • 65
  • 73
user1844666
  • 65
  • 1
  • 4
  • Create a parser, that uses [this](https://stackoverflow.com/questions/18265935/python-create-list-with-numbers-between-2-values). – Torxed May 31 '20 at 20:44
  • [intspan](https://stackoverflow.com/questions/56926573/whats-wrong-with-my-use-of-generator-expression/56926631#56926631) will do the conversion. – Chris Charley May 31 '20 at 22:01
  • This should've been closed as a duplicate of [How to convert numeric string ranges to a list in Python](https://stackoverflow.com/q/6405208/7851470) – Georgy Jun 13 '20 at 22:28

2 Answers2

3

You can use re module for the task.

For example:

import re

strings = ["1-4, 7, 9-11",
"5-9",
"1,2,3,10,11",
"1-3,5,6,7"]

for s in strings:
    out = []
    for a, b in re.findall(r'(\d+)-?(\d*)', s):
        out.extend(range(int(a), int(a)+1 if b=='' else int(b)+1))
    print('Input = {:<20} Output = {}'.format(s, out))

Prints:

Input = 1-4, 7, 9-11         Output = [1, 2, 3, 4, 7, 9, 10, 11]
Input = 5-9                  Output = [5, 6, 7, 8, 9]
Input = 1,2,3,10,11          Output = [1, 2, 3, 10, 11]
Input = 1-3,5,6,7            Output = [1, 2, 3, 5, 6, 7]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

This should do the trick! I used an example you gave, you may use it in a loop for example for the rest of the strings. We split each part by commas. If the part has "-" in it, then it must be a range so we find the location of the "-" sign and take the number before it as the start and the num after it as the end of the range. Note that range(N) gives you all numbers until N-1 so we used plus 1.

nums = "1-4, 7, 9-11"  # example list
nums_list = nums.split(",")  # seperate to parts

total_list = []

for part in nums_list:
    part = part.strip()
    if "-" in part:  # if it is a range of nums
        mid = part.find("-") 
        for i in range(int(part[:mid]), int(part[mid+1:])+1): # append the range
            total_list.append(i)
    else:
        total_list.append(int(part))  # else append the num

print(total_list)
snatchysquid
  • 1,283
  • 9
  • 24