Using Python “not in” operator in the string you can check if the string contains another string. Python string supports in operator. The in-operator syntax is:
sub in str
Not in
sub not in str
Python is not in string
Simple example code checks if a string is part of another string or not. It returns false
if the “sub” string is part of “str”, otherwise it returns true
.
str1 = 'I love Python Programming:'
str2 = 'Python'
str3 = 'Java'
print(f'"{str1}" contains "{str2}" = {str2 not in str1}')
print(f'"{str1}" contains "{str2.lower()}" = {str2.lower() not in str1}')
print(f'"{str1}" contains "{str3}" = {str3 not in str1}')
if str2 in str1:
print(f'"{str1}" contains "{str2}"')
else:
print(f'"{str1}" does not contain "{str2}"')
Output:
The simplest and fastest way to check whether a string contains a substring or not in Python is by using the “in” operator, which is used as a comparison operator. Some other Python methods such as find(), index(), count(), etc. also help to Check if a string contains a substring.
Do comment if you have any doubts or suggestions on this Python string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.