Skip to content Skip to sidebar Skip to footer

Python - Check If A Word Is In A String

How to tell if a word is in a string? Words are not sub-strings. I don't want to use regex. Using only in is not enough... Something like: >>> wordSearch('sea', 'Do seah

Solution 1:

What about to split the string and strip words punctuation, without forget the case?

w in [ws.strip(',.?!') for ws in p.split()]

Maybe that way:

def wordSearch(word, phrase):
    punctuation = ',.?!'
    return word in [words.strip(punctuation) for words in phrase.split()]

    # Attention about punctuation (here ,.?!) and about split characters (here default space)

Sample:

>>> print(wordSearch('Sea'.lower(), 'Do seahorses live in reefs?'.lower()))
False
>>> print(wordSearch('Sea'.lower(), 'Seahorses live in the open sea.'.lower()))
True

I moved the case transformation to the function call to simplify the code...
And I didn't check performances.


Solution 2:

Use the in keyword:

something like this:

print('Sea'in 'Seahorses live in the open sea.')

If you don't want it to be case sensitive. convert all the sting to lower or upper

something like this:

string1 = 'allow'
string2 = 'Seahorses live in the open sea Allow.'

print(string1.lower() in string2.lower())

or you may use the find method like this:

string1 = 'Allow'
string2 = 'Seahorses live in the open sea Allow.'

if string2.find(string1) !=-1 :
    print('yes')

If you want to match the exact word:

string1 = 'Seah'
string2 = 'Seahorses live in the open sea Allow.'

a = sum([1 for x in string2.split(' ') if x == string1])

if a > 0:
    print('Yes')

else:
    print('No')

update

you need to ignore all the punctuation so use this.

def find(string1, string2):
    lst = string2.split(' ')
    puctuation = [',', '.', '!']
    lst2 = []
    
    for x in lst:
        for y in puctuation:
            if y in x[-1]:
                lst2.append(x.replace(y, ''))
        lst2.append(x)
    
    lst2.pop(-1)    
    a = sum([1 for x in lst2 if x.lower() == string1.lower()])
    if a > 0:
        print('Yes')
    
    else:
        print('No')

find('sea', 'Seahorses live in the open sea. .hello!')

Post a Comment for "Python - Check If A Word Is In A String"