Check if two strings are equal ignoring case
Check if two strings are equal ignoring case
Two strings are said to be equal ignoring case, if and only if the two strings have same length and same characters (case insensitive) at respective positions.
To check if two strings are equal ignoring case, convert both the strings to lowercase or uppercase, and compare these using Equal-to Comparison Operator.
Syntax
The syntax of the boolean expression using Equal-to operator to check if the strings str1
and str2
are equal ignoring the case is
str1.lower() == str2.lower()
or
str1.upper() == str2.upper()
Examples
1. Check if two given strings are equal using lower() method
In the following program, we take same string value in str1
and str2
variables but different case characters, and check if these two strings are equal programmatically ignoring the case using String.lower() method.
Python Program
str1 = 'Hello World'
str2 = 'HELLO WORLD'
if str1.lower() == str2.lower() :
print('two strings are equal ignoring case')
else :
print('two strings are not equal ignoring case')
Output
two strings are equal ignoring case
2. Check if two given strings are equal using upper() method
In the following program, we will use String.upper() method to check if str1
and str2
strings are equal ignoring the case.
Python Program
str1 = 'Hello World'
str2 = 'HELLO WORLD'
if str1.upper() == str2.upper() :
print('two strings are equal ignoring case')
else :
print('two strings are not equal ignoring case')
Output
two strings are equal ignoring case
3. Negative scenario (different string values)
In the following program, we take different string values in str1
and str2
variables, and check if these two strings are equal or not ignoring the case.
Python Program
str1 = 'Hello World'
str2 = 'HELLO'
if str1.upper() == str2.upper() :
print('two strings are equal ignoring case')
else :
print('two strings are not equal ignoring case')
Output
two strings are not equal ignoring case
Summary
In this tutorial of Python Examples, we learned how to check if two strings are equal ignoring the case using String.lower() or String.upper() method, and equal-to operator, with the help of well detailed examples.