Skip to content

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:

Use the "in" keyword to check if a word is in a string

python
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:

output

console
'World' is in the string 'Hello, World!'

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:

Use string find() method to check the word's index if present in the string

python
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:

another output

console
'World' is in the string 'Hello, World!'

Dual-run preview — compare with live Symfony routes.