Reputation: 16275
Say, for example, I want to check if the word test
is in a string. Normally, I'd just:
if 'test' in theString
But I want to make sure it's the actual word, not just the string. For example, test
in "It was detestable" would yield a false positive. I could check to make sure it contains (\s)test(\s)
(spaces before and after), but than "...prepare for the test!" would yield a false negative. It seems my only other option is this:
if ' test ' in theString or ' test.' in theString or ' test!' in theString or.....
Is there a way to do this properly, something like if 'test'.asword in theString
?
Upvotes: 3
Views: 200
Reputation: 28846
import re
if re.search(r'\btest\b', theString):
pass
This will look for word boundaries on either end of test
. From the docs, \b
:
Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character.
Upvotes: 10