Normalize a string

Tags
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.

  1. # Get user input.
  2. love_dogs = input('Do you love dogs (Y/N)? ')
  3. # Normalize.
  4. 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.

  1. # Get user input.
  2. love_dogs = input('Do you love dogs (Y/N)? ')
  3. # Normalize.
  4. love_dogs_normalized = love_dogs.strip().lower()