To check if a string contains a substring and ignore the case of the characters in the string, you can use the Python in operator and the lower() function.
s = "this IS a StrING"
def containsCaseInsensitive(substring, string):
if substring.lower() in string.lower():
return True
else:
return False
print(containsCaseInsensitive("is",s))
print(containsCaseInsensitive("THIS",s))
print(containsCaseInsensitive("z",s))
#Output:
True
True
False
You can also use the Python upper() function if you want.
s = "this IS a StrING"
def containsCaseInsensitive(substring, string):
if substring.upper() in string.upper():
return True
else:
return False
print(containsCaseInsensitive("is",s))
print(containsCaseInsensitive("THIS",s))
print(containsCaseInsensitive("z",s))
#Output:
True
True
False
When processing string variables, the ability to check certain conditions is valuable.
One such case is if you want to perform a case-insensitive search and see if a string is contained in another string if we ignore case.
In Python, we can create a contains case insensitive function easily with the Python in operator and the lower() function.
in in Python allows us to see if a string is contained in a string, but is case sensitive.
If you want to check if a string is contained in another and ignore case, we need to use lower() to convert both strings to lowercase.
Then you can see if the lowercase string is contained in the other lowercase string.
Below is an example showing you how to see if a string is contained in another string ignoring case in Python.
s = "this IS a StrING"
def containsCaseInsensitive(substring, string):
if substring.lower() in string.lower():
return True
else:
return False
print(containsCaseInsensitive("is",s))
print(containsCaseInsensitive("THIS",s))
print(containsCaseInsensitive("z",s))
#Output:
True
True
False
Hopefully this article has been useful for you to check if a string contains another string case insensitive in Python.