How do I check for an EXACT word in a string in python

You can use the word-boundaries of regular expressions. Example:

import re

s="98787This is correct"
for words in ['This is correct', 'This', 'is', 'correct']:
    if re.search(r'\b' + words + r'\b', s):
        print('{0} found'.format(words))

That yields:

is found
correct found

EDIT: For an exact match, replace \b assertions with ^ and $ to restrict the match to the begin and end of line.

Leave a Comment