If user input equals string, do something in Python

avatar

Borislav Hadzhiev

Last updated: Aug 22, 2022

banner

Photo from Unsplash

If user input equals string, do something in Python #

Use the equality operator to do something if a user input equals a string, e.g. if user_input == my_str:. The equality operator will return True if the user input equals the string and False otherwise.

main.py
# ✅ If user input equals string, do something user_input = input('Enter your favorite fruit: ') my_str = 'apple' if user_input == my_str: print('Correct') else: print('String does NOT match') # ------------------------------------------------------- # ✅ If user input equals one of multiple strings, do something user_input = input('Enter your favorite fruit: ') options = ('apple', 'banana', 'kiwi') if user_input in options: print('Correct') else: print('String does NOT match')

The first example uses the equality (==) operator to check if a user input equals a string.

main.py
user_input = input('Enter your favorite fruit: ') my_str = 'apple' if user_input == my_str: print('Correct') else: print('String does NOT match')
The equality operator returns True if the values on the left-hand and right-hand sides are equal and False otherwise.

If you need to check if a user input equals a string, ignoring the case, convert both strings to lowercase.

main.py
user_input = input('Enter your favorite fruit: ') my_str = 'apple' if user_input.lower() == my_str.lower(): print('Correct') else: print('String does NOT match')

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

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

Both strings have to either be lowercase or uppercase to perform a case-insensitive comparison.

If you need to check if a user input value is equal to one of multiple values, use the in operator.

main.py
user_input = input('Enter your favorite fruit: ') options = ['apple', 'banana', 'kiwi'] if user_input in options: print('Correct') else: print('String does NOT match')

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

main.py
options = ['apple', 'banana', 'kiwi'] print('apple' in options) # 👉️ True print('melon' in options) # 👉️ False

The example checks if the input value is equal to any of the values in the options list.

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.