Python Program to compare two strings by ignoring case


In python we can use the comparison operators like “==”,”!=”, “<”,”>”,”<=”,”>=” and python inbuilt function like lower() and upper() methods to compare two strings by ignoring case. Strings are character sequences enclosed in double quotes. These operators compare strings based on the Unicode code points assigned to each character of the string. In this article, we will understand how we can compare two strings by ignoring cases of the string.

Comparing Strings Ignoring Case

To compare two strings in Python while ignoring the case, we can use the lower() or upper() function which converts the string to lowercase or uppercase respectively. Once the strings are fully converted in either lowercase or uppercase then we can compare the strings ignoring the case of the string.

Example 1

In the below example, we use the lower() method to convert the string into lowercase. Then we compare both strings using the “==” operator. Since the two strings are identical the output of the code will be “The strings are equal, ignoring case”.

string1 = "Hello"
string2 = "hello"
if string1.lower() == string2.lower():
   print("The strings are equal, ignoring case.")
else:
   print("The strings are not equal, ignoring case.")

Output

The strings are equal, ignoring case.

Example 2

We can also prompt the user to enter his own string for comparison. In the below example, we take two strings and then we convert both strings to lowercase using the lower() function and then compare both strings using the “==” operator.

string1 = "welcome To tutorials Point"
string2 = "Welcome to Tutorials point"
if string1.lower() == string2.lower():
   print("The strings are equal, ignoring case.")
else:
   print("The strings are not equal, ignoring case.")

Output

The strings are equal, ignoring case.

Conclusion

Comparing strings in Python can be done by using the python inbuilt function lower() and upper() which converts the string to lower and uppercase respectively before comparison. This case-insensitive comparison is widely used in many operations in Python. In this article, we understood how we can compare strings by ignoring the case of the strings.

Updated on: 17-Apr-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements