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.

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)

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.