Last modified: Jan 10, 2023 By Alexander Williams

Python: Ignore Case and check if strings are equal

In programming, uppercase and lowercase letters are not equal. For example:

"a" == "A"
# False

This tutorial will teach us to ignore cases when checking if two strings are equal.

Ignore cases and check using lower()

The lower() built-in function converts uppercase letters to lowercase.

lower() built-in function

Syntax:

str.lower()

Example:

print("HELLO Python".lower())

Output:

hello python

How to use lower() to ignore cases

When checking, we'll use the lower() function to convert uppercase characters to lowercase of two strings.

Example

str1 = "HELLO PYTHON"
str2 = "hello python"

# Ignore Cases and check if equal
print(str1.lower() == str2.lower())

Output:

True

As you can see, although the two strings have different cases, the program returns True.

How to use check with if Condition statement

If we want to do something after checking, we need to use the if Condition statement.

Example:

str1 = "HELLO PYTHON"
str2 = "hello python"

if str1.lower() == str2.lower():
    # Do something
    print(True)
else:
    # Do something
    print(False)

Output:

True

Ignore cases and check using upper()

The upper() built-in function converts lowercase characters to uppercase.

upper() built-in function

syntax:

str.upper()

Example:

# Convert to uppercase
print("hello Python".upper())

Output:

HELLO PYTHON

How to use upper() to ignore cases

The following example will show us how to use upper() to ignore cases.

Example

str1 = "Hello Python"
str2 = "helLo pytHon"

# Ignore Cases and check if equal
print(str1.upper() == str2.upper())

Output:

True

As you can see, we've done the same thing like the lower() function.

Conclusion

In this tutorial, we've learned two methods to ignore cases when checking strings if they are equal. Both ways work very well. Choose whatever you like.