Check if a word is in a string in Python
You can use the in
keyword to check if a word is in a string in Python. Here is an example code snippet:
string = "Hello, World!"
word = "World"
if word in string:
print(f"'{word}' is in the string '{string}'")
else:
print(f"'{word}' is not in the string '{string}'")
This code will output:
'World' is in the string 'Hello, World!'
Watch a video course
Python - The Practical Guide
You can also use the str.find()
method to check the word's index if present in the string. If the word is present it returns the starting index of the word otherwise it returns -1. Here is an example code snippet:
string = "Hello, World!"
word = "World"
if string.find(word) != -1:
print(f"'{word}' is in the string '{string}'")
else:
print(f"'{word}' is not in the string '{string}'")
This code will also output:
'World' is in the string 'Hello, World!'