Check String contains Substring in Python

  • Post category:String

To check if a string contains substring in Python, you can use the in operator. The in operator returns True if the string is a substring of the other string.

Let’s code it.

Step 1: Create two strings

str1 = "Python"
str2 = "Py"

print("str1 = ", str1)
print("str1 type = ", type(str1))

print("str2 = ", str2)
print("str2 type = ", type(str2))

Step 2: Check if string is substring

if str2 in str1:
    print("Substring")
else:
    print("Not Substring")
str1 =  Python
str1 type =  <class 'str'>
str2 =  Py
str2 type =  <class 'str'>
Substring

Free resources to learn advanced skills: AiHints and CodeAllow