using input is there a way to input a range

Viewed 48

I have some code which takes a series of numbers separated by commas using input(). While that works fine I would like the user to be able to put in these numbers but also include a range if they wanted to.

input = 1,2,3 # works fine

input = 1,2,3,4-9,15 # no idea if this can work

I have no idea if this is best pursued with a regex as they totally mystify me tbh.

Code

def convert_to_int(user_input_str):
    input_list_str = list(user_input_str.split(","))
    number_list = []
    for n in input_list_str:
        number_list.append(int(n))
    return number_list


if __name__ == "__main__":
    #manual_testing()
    print("enter list, each integer separated by a comma")
    user_input_str = input()
    print("From user : ", convert_to_int(user_input_str))

Input

1,2,3

Returns

From user :  [1, 2, 3]

Desired functionality

input

1,2,3,9-14,21

Desired output

From user :  [1, 2, 3, 9, 10, 11, 12, 13, 14, 21]
3 Answers

Just add another checker for - and add the range to the list:

def convert_to_int(user_input_str):
    input_list_str = list(user_input_str.split(","))
    number_list = []
    for n in input_list_str:
        if '-' not in n:
            number_list.append(int(n))
        else:
            number_list.extend(range(int(n.split('-')[0]), int(n.split('-')[1]) + 1))
    return number_list


if __name__ == "__main__":
    #manual_testing()
    print("enter list, each integer separated by a comma")
    user_input_str = input()
    print("From user : ", convert_to_int(user_input_str))

Try regex:

import re
def convert_to_int(user_input_str):
    input_list_str = list(re.split('\D', user_input_str))
    number_list = []
    for n in input_list_str:
        number_list.append(int(n))
    return number_list


if __name__ == "__main__":
    #manual_testing()
    print("enter list, each integer separated by a comma")
    user_input_str = input()
    print("From user : ", convert_to_int(user_input_str))
    

Try this:

import re
def convert_to_int(user_input_str):
   
   input_list_str = user_input_str.split(",")
   number_list = []
   
   for n in input_list_str:
      if '-' in n: 
         number_list.extend(x for i,j in re.findall(r'(\d+)-(\d+)',user_input_str.replace(' ','')) for x in range(int(i),int(j)+1))
      else:
          number_list.append(int(n))

   return number_list



if __name__ == "__main__":
  
   print("enter list, each integer separated by a comma")
   user_input_str = input()
   print("From user : ", convert_to_int(user_input_str))
Related