Check if a word is in a string in Python
I’m working with Python, and I’m trying to find out if you can tell if a word is in a string. I have found some information about identifying if the word is in the string — using .find , but is there a way to do an if statement. I would like to have something like the following:
if string.find(word): print("success")
14 Answers 14
if word in mystring: print('success')
just as a caution, if you have a string «paratyphoid is bad» and you do a if «typhoid» in «paratyphoid is bad» you will get a true.
How is this the accepted answer. It just checks whether a sequence of characters (not a word) appear in a string
if 'seek' in 'those who seek shall find': print('Success!')
but keep in mind that this matches a sequence of characters, not necessarily a whole word — for example, ‘word’ in ‘swordsmith’ is True. If you only want to match whole words, you ought to use regular expressions:
import re def findWholeWord(w): return re.compile(r'\b()\b'.format(w), flags=re.IGNORECASE).search findWholeWord('seek')('those who seek shall find') # -> findWholeWord('word')('swordsmith') # -> None
Is there a really fast method of searching for multiple words, say a set of several thousand words, without having to construct a for loop going through each word? I have a million sentences, and a million terms to search through to see which sentence has which matching words. Currently it’s taking me days to process, and I want to know if there’s a faster way.
If you want to find out whether a whole word is in a space-separated list of words, simply use:
def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ') contains_word('the quick brown fox', 'brown') # True contains_word('the quick brown fox', 'row') # False
This elegant method is also the fastest. Compared to Hugh Bothwell’s and daSong’s approaches:
>python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')" 1000000 loops, best of 3: 0.351 usec per loop >python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'\b()\b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')" 100000 loops, best of 3: 2.38 usec per loop >python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')" 1000000 loops, best of 3: 1.13 usec per loop
Edit: A slight variant on this idea for Python 3.6+, equally fast:
def contains_word(s, w): return f' ' in f' '
Python: Check if String Contains Substring
Checking whether a string contains a substring aids to generalize conditionals and create more flexible code. Additionally, depending on your domain model — checking if a string contains a substring may also allow you to infer fields of an object, if a string encodes a field in itself.
In this guide, we’ll take a look at how to check if a string contains a substring in Python.
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.
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 also need to know the position of the substring, as opposed to just its existence within the full string. The method itself returns the index:
print(fullstring.index(substring)) # 1
Though — for the sake of checking whether a string contains a substring, this is a verbose approach.
The String.find() Method
The String class has another method called find() which is more convenient to use than index() , mainly 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:
Free eBook: Git Essentials
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!
fullstring = "StackAbuse" substring = "tack" if fullstring.find(substring) != -1: print("Found!") else: print("Not found!")
Naturally, it performs the same search as index() and returns the index of the start of the substring within the parent string:
print(fullstring.find(substring)) # 1
Regular Expressions (RegEx)
Regular expressions provide a more flexible (albeit more complex) way to check strings for pattern matching. With Regular Expressions, you can perform flexible and powerful searches through much larger search spaces, rather than simple checks, like previous ones.
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, or if you’re dealing with large search spaces. Otherwise the complication and slower speed of regex should be avoided for simple substring matching use-cases.
About the Author
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.