0

I need to only allow integers and the letters "d" and "r" from raw input otherwise I need to run an exception. For example:
You entered 's' this is invalid
I have tried to use try/except statements but can't work it out. Is this the best way? Can someone help? Thanks.

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by vegaseat
0

It is generally done with a list.

def test_input(input_str):
   accept_list = []
   for x in range(0, 10):
      accept_list.append(str(x))
   accept_list.append("d")
   accept_list.append("r")

   for character in input_str:
      if character not in accept_list:
         return False

   return True
#
#  test it
input_string = "a"
print input_string, test_input(input_string)
input_string = "3A3"
print input_string,  test_input(input_string)
input_string = "9d3"
print input_string,  test_input(input_string)
0

Or you can do it this way ...

# these are the accepted characters in the input string
accepted = '0123456789dr'
while True:
    mystr = raw_input("Enter data (allowed are integers and 'dr'): ")
    if all(x in accepted for x in mystr):
        break
    print("unaccepted characters in input, try again")

print(mystr)  # test

Note:
Function all() needs Python25 or higher.

Edited by vegaseat: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.