In this tutorial, we will learn how to make a string case-insensitive in Python. Sometimes, while working with strings, we may need to compare two or more strings and perform some operations regardless of their case (uppercase or lowercase). In such scenarios, making a string case-insensitive will be helpful. We will discuss different methods to achieve this.
Method 1: Using the lower() or upper() function
A simple way to make a string case-insensitive is by converting all characters of the string to either lowercase or uppercase using the lower() or upper() function. Then, the next time we need to compare two strings, both of them will have the same case and our comparisons will be case-insensitive.
1 2 3 4 5 6 7 8 9 10 11 12 |
string1 = "helLo WorlD" string2 = "Hello World" # Converting the strings to lowercase string1 = string1.lower() string2 = string2.lower() # Comparing the strings if string1 == string2: print("The two strings are the same.") else: print("The two strings are different.") |
Output
The two strings are the same.
Method 2: Using the casefold() function
Instead of using lower() or upper(), we can use the casefold() function, which is specifically designed for caseless string comparisons. It converts the string to lowercase and also handles special cases, such as special Unicode characters, which makes it more suitable for case-insensitive comparisons in a multilingual context.
1 2 3 4 5 6 7 8 9 10 11 12 |
string1 = "HELLO WORLD" string2 = "Hello World" # Using casefold() function string1 = string1.casefold() string2 = string2.casefold() # Comparing the strings if string1 == string2: print("The two strings are the same.") else: print("The two strings are different.") |
Output
The two strings are the same.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Method 1 - Using lower() function string1 = "helLo WorlD" string2 = "Hello World" string1 = string1.lower() string2 = string2.lower() if string1 == string2: print("The two strings are the same.") else: print("The two strings are different.") # Method 2 - Using casefold() function string1 = "HELLO WORLD" string2 = "Hello World" string1 = string1.casefold() string2 = string2.casefold() if string1 == string2: print("The two strings are the same.") else: print("The two strings are different.") |
Conclusion
In this tutorial, we discussed two different methods for making a string case-insensitive in Python: using the lower() or upper() functions, and using the casefold() function. The latter is more suitable for handling special Unicode characters in case-insensitive string comparisons. Now you can perform case-insensitive string comparisons in Python with ease!