Summary
Simplify string validity checks by converting user input to a standard form.
Situation
You want to get a string input from a user, and validate it. For user convenience, you want to let them type any mix of upper- and lowercase, and have extra spaces at the start and end of the input.
Action
Here's an example.
- # Get user input.
- love_dogs = input('Do you love dogs (Y/N)? ')
- # Normalize.
- love_dogs = love_dogs.strip().lower()
This version replaces the user's input in the variable love_dog
with the normalized version.
Sometimes you want to keep the original input, but still normalize for testing. Put the normalized value into a different variable.
- # Get user input.
- love_dogs = input('Do you love dogs (Y/N)? ')
- # Normalize.
- love_dogs_normalized = love_dogs.strip().lower()
Where referenced