Shweta Chandel
Shweta Chandel

Reputation: 895

Search for a word in a list

I want to search for the existence of the word hi.

import re
word = 'hi?'

cleanString = re.sub('\W+',' ', word)
print(cleanString.lower())

GREETING_INPUTS = ("hello", 'hi', 'hii', "hey")
if cleanString.lower() in GREETING_INPUTS:
    print('yes')
else:
    print('no')

When word = 'hi', it prints yes. But for word = 'hi?', it prints no. Why is it so and please suggest any solution.

Upvotes: 0

Views: 82

Answers (1)

U13-Forward
U13-Forward

Reputation: 71560

Replace this line:

cleanString = re.sub('\W+',' ', word)

With:

cleanString = re.sub('\W+','', word)

Because you're replacing all the matches of '\W+' with ' ', a space, so the string would be 'hi ', so then you need to replace it with empty string '' for it to work, the string would become 'hi'

Upvotes: 1

Related Questions