In Python, checking if a string contains a specific word or substring can be done using various methods. Each method has its own use cases and advantages. Here are some common methods:

1. Using the in Operator: This is the most straightforward way to check if a substring exists in a string.

text = "Hello, world!"
if "world" in text:
    print("The word 'world' is found.")

2. Using str.find() Method: This method returns the lowest index in the string where the substring is found. If the substring is not found, it returns -1.

text = "Hello, world!"
if text.find("world") != -1:
    print("The word 'world' is found.")

3. Using str.index() Method: Similar to find(), but raises a ValueError if the substring is not found. Useful if you want to handle the absence of the substring as an exception.

text = "Hello, world!"
try:
    text.index("world")
    print("The word 'world' is found.")
except ValueError:
    print("The word 'world' is not found.")

4. Using Regular Expressions (re module): This is a powerful method, especially when you need more complex pattern matching, such as case-insensitive search.

import re
text = "Hello, world!"
if re.search(r"\bworld\b", text):
    print("The word 'world' is found.")

The \b in the regular expression ensures that you're searching for the word "world" as a whole word, not as part of another word (like "worldwide").

5. Using str.count() Method: This method returns the number of occurrences of the substring in the string.

text = "Hello, world!"
if text.count("world") > 0:
    print("The word 'world' is found.")

6. Using List Comprehension with split(): This method involves splitting the string into words and then checking if the word exists in the list. This is useful if you want to check for whole words rather than substrings.

text = "Hello, world!"
if "world" in text.split():
    print("The word 'world' is found.")

Each of these methods can be used depending on the specific requirements of your task, such as the need for case.

Simon

102 Articles

I love talking about tech.