Checking Whether a String Contains a String in Python, With Examples

Python String Contains

This article will show you how to check if a string contains another string in the Python programming language.

PHP and Javascript both have similar functions included:

PHP strpos Function: Check if a String Contains Another String

Javascript String includes() Method – Check if a String Contains Another String

Python has several methods for accomplishing the same thing – read on for how to do it.

Using in to Check if A String Contains a String in Python

The fastest and best way to check if a string contains a value in Python is to use the in operator:

if "screw" in "hello linuxscrew!": 
    print("Found!")

Or, to check if a string doesn’t contain a value:

if "screw" not in "hello linuxscrew!": 
    print("Not found!")

Using *string.find() to Check if A String Contains a String in Python

The string type in Python also has a built-in method for finding the index of a substring within a string.

The find() method will return the index of the string if it is found, or -1 if it is not (the index is the position of the found substring – as indexes start counting at position 0, -1 is used to signal that it isn’t present).

myString = "hello linuxscrew!"
if myString.find("screw") == -1:
    print("Not found!")
else:
    print("Found!")

Conclusion

It’s recommended you use the first method to check whether your string contains a value – that’s what the in statement is made for. Using string.find(), and other string methods that may return a value that can be used to test for the substring may work, but it’s not their intended use.

It’s also worth noting that Python won’t care whether the string being searched is in a whole word or just part of one – searching for “oo” in “Food is eaten” will return TRUE.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *