How to Compare Strings in Python Case Insensitively?

Estimated read time 1 min read

To compare strings in Python case insensitively, you can convert the strings to lowercase (or uppercase) using the str.lower() method and then perform the comparison. Here’s an example:

string1 = "Apple"
string2 = "apple"

if string1.lower() == string2.lower():
    print("The strings are equal (case-insensitive).")
else:
    print("The strings are not equal (case-insensitive).")

In this example, string1.lower() and string2.lower() convert both strings to lowercase before comparing them using the == operator. By converting both strings to lowercase, any differences in the letter case are ignored, resulting in a case-insensitive comparison.

The str.lower() method returns a new string where all characters are converted to lowercase. Similarly, you can use str.upper() to convert strings to uppercase for case-insensitive comparisons.

Note that when comparing strings case insensitively, you need to ensure that both strings are transformed to the same case (lowercase or uppercase) using lower() or upper() before making the comparison.

By comparing strings case insensitively, you can determine if they are equal regardless of differences in letter case.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply