Check text in string python

In this guide, we'll take a look at how to check if a string contains a substring in Python. As usual, each approach we'll cover has different pros and cons.

The in Operator

The easiest way to check if a Python string contains a substring is to use the in operator.

The in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring:

fullstring = "StackAbuse"
substring = "tack"

if substring in fullstring:
    print("Found!")
else:
    print("Not found!")

This operator is shorthand for calling an object's __contains__ method, and also works well for checking if an item exists in a list. It's worth noting that it's not null-safe, so if our fullstring was pointing to None, an exception would be thrown:

TypeError: argument of type 'NoneType' is not iterable

To avoid this, you'll first want to check whether it points to None or not:

fullstring = None
substring = "tack"

if fullstring != None and substring in fullstring:
    print("Found!")
else:
    print("Not found!")

The String.index() Method

The String type in Python has a method called index() that can be used to find the starting index of the first occurrence of a substring in a string.

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

If the substring is not found, a ValueError exception is thrown, which can be handled with a try-except-else block:

fullstring = "StackAbuse"
substring = "tack"

try:
    fullstring.index(substring)
except ValueError:
    print("Not found!")
else:
    print("Found!")

This method is useful if you need to know the position of the substring, as opposed to just its existence within the full string.

The String.find() Method

The String type has another method called find which is more convenient to use than index(), because we don't need to worry about handling any exceptions.

If find() doesn't find a match, it returns -1, otherwise it returns the left-most index of the substring in the larger string.

fullstring = "StackAbuse"
substring = "tack"

if fullstring.find(substring) != -1:
    print("Found!")
else:
    print("Not found!")

If you'd prefer to avoid the need to catch errors, then this method should be favored over index().

Regular Expressions (RegEx)

Regular expressions provide a more flexible (albeit more complex) way to check strings for pattern matching. Python is shipped with a built-in module for regular expressions, called re. The re module contains a function called search(), which we can use to match a substring pattern:

from re import search

fullstring = "StackAbuse"
substring = "tack"

if search(substring, fullstring):
    print "Found!"
else:
    print "Not found!"

This method is best if you are needing a more complex matching function, like case insensitive matching. Otherwise the complication and slower speed of regex should be avoided for simple substring matching use-cases.

This article was written by Jacob Stopak, a software consultant and developer with passion for helping others improve their lives through code. Jacob is the creator of Initial Commit - a site dedicated to helping curious developers learn how their favorite programs are coded. Its featured project helps people learn Git at the code level.

Check if String Contains Substring in Python

Checking if a string contains a substring is one of the most common tasks in any programming language. Python offers many ways to check if a string contains a substring. The simplest and fastest way to check whether a string contains a substring or not in Python is 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.

Using Python's "in" operator

The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .

output

Python "in" operator takes two arguments, one on the left and one on the right, and returns True if the left argument string is contained within the right argument string.

More on "in" operator

Check text in string python

Note: The "in" operator is case sensitive i.e, it will treat the Uppercase characters and Lowercase characters differently.

__contains__() function

Python String class has the __contains__() method that we can use to check if it contains another string or not. When we use Python "in" operator , internally it calls __contains__() function. The __contains__ method defines how instances of class behave when they appear at right side of in and not in operator. We can use this function directly too, but don't . Methods that start with underscores are considered semantically private , however it's recommended to use in operator for readability purposes.

Using Python's str.find() method

Another method you can use is the string.find() method . The find() method evaluate if the string contains a substring . If it does, the find() method returns the starting index of a substring within the string otherwise it returns -1 .

output

More on find() method

Check text in string python

Using str.find() method is the less Pythonic way , but it's still accepted. It's longer and a little bit more confusing, but it still gets the job done.

Using Python Regular Expression

Regular expression is widely used for pattern matching . Python has a built-in package called re , which can be used to work with Regular Expressions . The re module contains a function called search() , it can be used to check if a string contains the specified search pattern .

example

output

Using str.count() method

If you want to count the number of occurrences of a specific substring in a string, then you can use Python count() method . If the substring is not found in a string, the function returns 0 .

Check text in string python


How do I check if a string contains text?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do I check if a string contains a character in Python?

Using in operator The Pythonic, fast way to check for the specific character in a string uses the in operator. It returns True if the character is found in the string and False otherwise. ch = '. '

How do you check if a word is in a sentence Python?

If we want to check whether a given string contains a specified word in it or not, we can use the if/in statement in Python. The if/in statement returns True if the word is present in the string and False if the word is not in the string. The output shows that the word is is present inside the string variable string .