In this article, we will see different ways to perform a case-insensitive comparison in Python.
Using the ‘in’ operator
in
is used to check if the given value is present in the sequence or container. It returns True
if the value is found and False
if not.
By default ‘in’ performs the case-sensitive search, which means the upper case and lower case characters are considered as different.
Following is an example of case-sensitive in
string = "Hello, World!"
if "Hello" in string:
print("Found")
else:
print("Not found")
In the above example, the ‘in‘ operator performs a case-sensitive search. It will return True if the exact match of “Hello” is found in the string variable.
Case-insensitive ‘in’
To make the ‘in‘ case insensitive, we need to convert both the search value and values in the container to the same case, which means either lower case or upper case before we perform a search.
To perform a case-insensitive search using the ‘in’ operator, we need to convert both the search value and the container to the same case, either lower or upper case, before performing the search.
Example 1:
In the below example, the lower()
the method is used to convert both the value and string
to lowercase before performing the search.
string = "Hello, World!"
if "hello".lower() in string.lower():
print("Found")
else:
print("Not found")
Example 2:
In the below example, instead of lower(), we used the upper() method to convert both the search value and string
to convert to uppercase before performing the search. This ensures a case-insensitive search.
string = "Hello, World!"
if "HELLO".upper() in string.upper():
print("Found")
else:
print("Not found")
Using regex to perform case-insensitive compare
Another best approach to perform the case-insensitive search is by using regular expressions in Python. In the ‘re‘ module, we have a function called search(). By setting the flag re.IGNORECASE, this function performs a case-insensitive search.
import re
string = "Hello, World!"
if re.search("hello", string, re.IGNORECASE):
print("Found")
else:
print("Not found")
In the above example, re.search() is used with the re.IGNORECASE to enable the case-insensitive match. If the search pattern “hello” is found in the ‘string‘ it will print “Found“.