Ksisky
Ksisky

Reputation: 13

Check whether a string contains a specific word

Sorry if this is a duplicate, I looked around and couldn't find anything for my needs. I am a complete beginner to python, and I was wondering if there was a way to analyze a string to look for certain words using the built in modules. Any help is appreciated. Thanks.

Upvotes: 1

Views: 3162

Answers (2)

timgeb
timgeb

Reputation: 78690

To check whether a substring is in a string, you can issue

substring in mystring

Demo:

>>> 'raptor' in 'velociraptorjesus'
True

which interally calls the string's __contains__ method. Depending on your definition of a word, you'd need a regular expression to check whether your word is surrounded by word-boundaries (i.e. \b).

>>> import re
>>> bool(re.search(r'\braptor\b', 'velociraptorjesus'))
False
>>> bool(re.search(r'\braptor\b', 'veloci raptor jesus'))
True

If your definition of a word is that it is surrounded by whitespace (or nothing), split your string:

>>> 'raptor' in 'velociraptorjesus'.split()
False
>>> 'raptor' in 'veloci raptor jesus'.split()
True

If your definition of a word is more complex, use a positive lookbehind and lookahead, i.e.:

bool(re.search(r'(?<=foo)theword(?=bar)', 'some string'))

where foo and bar can be anything you wish to find before and after the word.

Upvotes: 2

AMACB
AMACB

Reputation: 1298

Here is a function that returns True if it can find a word in a string, and False if it can't.

def isWordIn(word, string):
    return not(string.find(word) == -1)

Upvotes: 0

Related Questions