2

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Haris Bade
  • 21
  • 1
  • Does this answer your question? [Split Strings into words with multiple word boundary delimiters](https://stackoverflow.com/questions/1059559/split-strings-into-words-with-multiple-word-boundary-delimiters) – linger1109 Jul 20 '22 at 03:29

2 Answers2

1

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]
mozway
  • 194,879
  • 13
  • 39
  • 75
0

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']
SergFSM
  • 1,419
  • 1
  • 4
  • 7