How do I check if a string contains a specific word?

 

To check if a string contains a specific word in Python, you can use the in keyword or the str.find() method. Here's how you can do it:

  1. Using the in keyword: The in keyword can be used to check if a substring (word) is present in a string. It returns a Boolean value (True or False).

    python
  • main_string = "Hello, how are you?" word = "how" if word in main_string: print("Word found") else: print("Word not found")
  • Using the str.find() method: The str.find() method returns the index of the first occurrence of the substring (word), or -1 if the substring is not found.

    python
    1. main_string = "Hello, how are you?" word = "how" index = main_string.find(word) if index != -1: print(f"Word found at index {index}") else: print("Word not found")

    Both methods are effective for checking whether a specific word exists within a string. Use the method that best fits your code's context and desired behavior.

    Comments