Make user input case-insensitive in Python

avatar

Borislav Hadzhiev

Last updated: Aug 26, 2022

banner

Photo from Unsplash

Make user input case-insensitive in Python #

Use the str.lower() method to make user input strings case-insensitive, e.g. user_input.lower(). Converting the strings we are comparing to the same case enables us to do a case-insensitive comparison.

main.py
user_input = input('Do you like pizza (yes/no): ') option_1 = 'yes' option_2 = 'no' if user_input.lower() == option_1.lower(): print('user typed yes') elif user_input.lower() == option_2.lower(): print('user typed no') else: print('Type yes or no')

make user input case insensitive

We used the input() function to take input from the user.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

We used the str.lower() function to convert both strings to lowercase to perform case-insensitive string comparison.

The str.lower method returns a copy of the string with all the cased characters converted to lowercase.

main.py
print('YES'.lower()) # 👉️ yes print('YES'.capitalize()) # 👉️ Yes print('yes'.upper()) # 👉️ YES

The method doesn't change the original string, it returns a new string. Strings are immutable in Python.

We could have achieved the same result by converting both strings to uppercase.

main.py
user_input = input('Do you like pizza (yes/no): ') option_1 = 'yes' option_2 = 'no' if user_input.upper() == option_1.upper(): print('user typed yes') elif user_input.upper() == option_2.upper(): print('user typed no') else: print('Type yes or no')

If the strings we are comparing are the same case, we can perform a case-insensitive comparison.

The str.upper method returns a copy of the string with all the cased characters converted to uppercase.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.