Python Basics

Python how to check if string contains substring?

In certain situation, you may want to know whether a sting contains another sub-string. Then the helpful tool that eases the process of knowing this is, “in” keyword. It checks whether the supplied element is present in the target element or not. If element is present then it would return true otherwise it would return false.

Example

sentence=”Once Upon a time”

#lets check if upon exists in the string sentence.

if “Upon” in sentence:

print(“Upon exists in the sentence”)

In certain cases we may not know what the string values in the variable, so in that case, cases sensitivity matters.

In the above example, instead of Upon, if I had checked upon then it would have returned false. Because in the sentence the string value has Upon but not upon.

So to better handle such situation, checking target object in lower case is a wise approach.

sentence=”Once Upon a time”

#lets check if upon exists in the string sentence.

if “upon” in sentence.lower():

print(“Upon exists in the sentence”)