Several modules are quite helpful for input validation. The string module contains constants for digits, upper and lower case, and more: string module. An example to verify that a string m is all digits:
1 2 3 4
def isdigits(m): import string return all(c in string.digits for c in m)
More powerful than directly writing a function to validate the form of a string is to use regular expressions and the re module. Here is a demonstration of validating that a string looks like a date, looking like "nn/nn/nnnn" (where each n is a digit). If you've never seen regular expressions before, don't feel that you need to understand all of this: it is just to show the flavor of what the re module does.
1 2 3 4 5
def datelike(m): import re s = re.compile('^[0-9]+/[0-9]+/[0-9]+$') p = s.findall(m) return len(p) == 1
The argument to the compile function is a cryptic string that somehow represents a "picture" of what a date should look like. The components of this picture are:
It should be clear that using regular expressions can be a tricky exercise. For most of the common kinds of input validation, it would be better to avoid writing your own functions (using the string module) or using regular expressions. Almost certainly, someone has already written some kind of validator, or if not a validator, a converter.
This might seem surprising: instead of validating the input or string variable, assume that it is valid and let the code attempt to convert it into a numeric type. The danger is that the program will have an error, but using a syntax feature called try/except (described in a later chapter), an error can be "intercepted". If there is no error, we know the input data was valid; and if an error had to be intercepted, then we know the input was invalid.
For dates, the recommended conversion is to use the datetime module, which has a function strptime that can interpret strings containing dates. The official documentation for datetime is not very helpful (better is to seek a specialized tutorial on how to use datetime and see examples).