Skip to content
Advertisement

List from string of digits

I’m getting a string from input() which consists of digits separated by spaces (1 5 6 3). First I’m trying to check that the input only consists of digits with the isdigit() function but because of the spaces I can’t get it to work. Then I convert the string to a list using the split() function.

What I need is to make a list from input and make sure it only consists of digits, else send a message and ask for a new input. Is it maybe possible to add a parameter to isdigit() that makes an exception for spaces?

Advertisement

Answer

What you’re describing is a look before you leap approach, i.e. checking first whether the input is conforming, and then parsing it. It’s more pythonic to use a Easier to ask for forgiveness than permission approach, i.e. just do it and handle exceptions:

s = raw_input() # input() in Python 3
try:
  numbers = map(int, s.split())
except ValueError:
  print('Invalid format')
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement