How to validate user input in python

python, string, user-input, validation

Solution

You can use `all`, `str.lower`, and a generator expression:

if not all(x in "agct " for x in Var1.lower()):
    print "Please input valid DNA sequence"
    sys.exit(1) 

In the above code, the last two lines will be run if any character in `Var1` is not one of the following:

"A", "T", "C", "G", " ", "a", "t", "c", "g"

Problem

I am brand new to python and I am trying to figure out how to validate user input. I want to ask the user to submit a DNA sequence and want to validate that it is a DNA sequence. Acceptable inputs can have upper or lowercase ATCGs and spaces and I'm not sure exactly how to do it. So far I can ask for the input but not verify it. ``` import sys Var1 = raw_input("Enter Sequence 1:") ``` I then want to do something like: ``` if Var1 != ATCG (somehow put 'characters that match ATCG or space) print "Please input valid DNA sequence" sys.exit() (to have it close the program) ``` Any help? I feel like this should be rather simple but I don't know how to specify that it can be any ATCG, atcg or space.

Original source

Related problems