Limiting Python input strings to certain characters

Does anybody know a way to restrict input to letters, numbers, spaces, and commas?

I’m trying to add a parameter to a user input, so it only allows them to enter specific characters like in that of a residential address.

What letters? ASCII or some specific locale? There is built-in string module which provides constants for ASCII letters, digits, punctuations and whitespaces.


Unless you are completely validating the address using a database of valid addresses (from the postal service of the country in question), you cannot be sure that some character will never occur in an address.

But if you need to check something that has a much more specific format (eg a US ZIP code, which consists only of digits and possibly a hyphen), you can construct a set from a string and see if that set is a subset of some other set. That’s the easiest way to check the alphabet of a string. That’s not the same as checking its format, though (eg “90-12-345” is not a valid US ZIP code), so first you have to decide what kind of validation you’re actually doing.

Checking for specific characters (as in your example) is not hard. The real challenge is checking that any combination of characters, makes sense. As an example, the input could be (again, based on your example) 1022a Main Str33t which would pass any check based on allowing numbers, spaces and alpha characters, but to the human eye (or brain) is clearly wrong. So, what you’ll have to do is to also have, what amounts to, a spell check as well.