Case-Insensitive String Comparisons in Python
String manipulation and comparison is often an essential part of any computer program or website script. Python has some different string functions and methods available to use to compare strings, but none of them are case-insensitive. However, you can combine some of the functionality available to create your own case-insensitive string comparison methods.
-
Comparison
-
When comparing two strings, use the "upper" or "lower" method to temporarily convert the two strings to uppercase or lowercase, then use the double equals sign operator to compare the two strings to each other. For example, type "var1.lower() == var2.lower()" to compare them. This is a Boolean operation that returns either true or false. If the two strings have the same characters and punctuation, regardless of case, this comparison returns true. Otherwise, it returns false.
Function
-
You can create a case-insensitive string comparison function and use it in your Python program. Define the function to accept two string variables as parameters, then write an if statement that converts both to lowercase and uses the double equals sign operator to compare them. If the two strings are equal, have the function return a value to inform the user the two are equal, and if the strings are not equal, inform the user appropriately. Alternatively, you can simply type "return var1.lower() == var2.lower()" as the only line in the function to return just true or false.
-
Performance
-
While this user-defined, case-insensitive string comparison function quickly compares two strings for equality, it also needs to allocate space in memory for the temporary storage of the two strings converted to lowercase. The program destroys these two objects as soon as the function exits. The initial strings themselves remain unmodified; using the "lower" method for comparison purposes does not change their values so you can use them elsewhere in the program without having to change anything back.
Uses
-
The need for a case-insensitive string comparison function exists in several situations. For example, you may use it in a Web script where you show the user a CAPTCHA image with characters and numbers, and you need him to type them in to validate his identity. Generally, these images do not care about letter case, so a case-insensitive comparison here works. Another example involves a search script where you prompt the user to search for something by typing in keywords. Because he does not care about the letter case and just wants his results, using a case-insensitive comparison lets you return those results that best fit the search.
-