Last modified: Aug 10, 2023 By Alexander Williams
How to Find Word in String Python
There are three main methods to find a word in a string in Python:
- The
in
keyword - The
str.find()
method - Regular expression
1. The "in" keyword method
In Python, the in
keyword is used as a membership operator. We can use this operator to find the word in a string.
Here is an example:
text = "This is a sample sentence."
word_to_find = "sample"
if word_to_find in text:
print("Word found!")
else:
print("Word not found.")
Output:
Word found!
As you can see, we've found the word "sample" in the text.
the str.find() method
The str.find()
method returns the index of the substring if it exists or -1 if it does not exist. To find a word in a string using the str.find()
method, you can use the following example:
text = "This is a sample sentence."
word_to_find = "sample"
index = text.find(word_to_find)
if index != -1:
print(f"Word found at index {index}.")
else:
print("Word not found.")
Regular expressions method
Another method to find a word in a string is using regular expressions. To find a word in a string using regular expressions, use the following example:
import re
text = "This is a sample sentence."
word_to_find = "sample"
if re.search(r'\b' + re.escape(word_to_find) + r'\b', text):
print("Word found!")
else:
print("Word not found.")
However, in the above example, we've used the re.search()
function to search for the pattern in the string.
The re.search()
function returns a match object if the pattern is found in the string and None
if the pattern is not found.