Home > Enterprise >  Multiple input split() method types for the same variable
Multiple input split() method types for the same variable

Time:07-20

The following code will get a list as input, and it will use the split method to split the input list with a space.

student_heights = input("Input a list of student heights ").split()
for n in range(0, len(student_heights)):
  student_heights[n] = int(student_heights[n])

If I wanted to split with comma, I will just ad a comma on the split() method above and that would be split(", ")

My question is, what if I want it separated both with a space and with , at the same time depending on the user so the user can input the list comma separated or non comma separated. I tried and/or but no luck so far.

CodePudding user response:

If you expect only integers, you might want to split using a regex for non digits:

import re
student_heights = list(map(int, re.split(r'\D ',  input("Input a list of student heights ").strip())))
print(student_heights)

NB. to limit the split to space and comma, use r'[, ]' in re.split, or r'[, ] ' for one or more of those characters, but be aware that any incorrect input will trigger an error during the conversion to int.

example:

Input a list of student heights 1 23,  456
[1, 23, 456]

Alternative with re.findall:

student_heights = list(map(int, re.findall(r'\d ', input("Input a list of student heights ")))

and for floats:

student_heights = list(map(float, re.findall(r'\d (?:\.\d*)?', input("Input a list of student heights "))))

example:

Input a list of student heights 1, 2.3  456.

[1.0, 2.3, 456.0]

CodePudding user response:

you can use replace method as well:

student_heights = input("Input a list of student heights ").replace(',',' ').split()

student_heights
>>> out
'''
Input a list of student heights 12,15, 20 25
['12', '15', '20', '25']
  • Related