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,
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.
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
upper() before making the comparison.
By comparing strings case insensitively, you can determine if they are equal regardless of differences in letter case.