Python string contains case insensitive | Example code

Use the in operator with the lower() or upper() function and a generator expression to check if a string is in a list of strings to check the string contains case insensitive in Python.

Example string contains case insensitive in Python

Simple example code. The list of strings matches with if there is an element of the list of strings that matches the string character for character.

list1 = ["Apple", "Lenovo", "HP", "Samsung", "ASUS"]

s = "lenovo"
s_lower = s.lower()

res = s_lower in (string.lower() for string in list1)

print(res)

Output: True

Python string match ignore-case

Convert strings into lower or upper case. This is if you’re doing the exact comparison.

str1 = "Hello"
str2 = "HELLO"

if str1.lower() == str2.lower():
    print('Both Strings are same')
else:
    print('Strings are not same')

Output:

Python string contains case insensitive

Comparision string case insensitive

if you’re doing a substring comparison.

str1 = "Messi is the best SoCceR player"
if "soccer" in str1.lower():
    print("Contain soccer")

if "Player" in str1:
    print("Contain football")

Output:

Contain soccer

How to make a string case insensitive in python

Answer: Make string lowercase or uppercase before matching it.

if thing.lower() == "text":

Or

Assert.IsTrue(text.ToUpper().Contains("Sample".ToUpper()));

Do comment if you have any doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.