Pallav Mishra
Pallav Mishra

Reputation: 15

Finding a word in a string

The following simple code works if one needs to find a whole word in a sentence string. Can anyone critique it, or find boundary conditions where this may fail?

a = input("Enter a sentence:")
w = input ("Enter a word to be found in the sentence")
if w.lower() in a.lower():
   print("It is present")
else:
   print("It is not present")

Upvotes: 1

Views: 132

Answers (2)

a121
a121

Reputation: 786

As per @Amadan's comment,

It depends more on the interpretation of the question. Is the word "car" found in the sentence "I like your scarf"? Some people will say yes — there is "car" inside "scarf" — and for those people, your code works correctly.

For this, your code works perfectly fine.

a = input("Enter a sentence:")
w = input ("Enter a word to be found in the sentence:")
if w.lower() in a.lower():
   print("It is present")
else:
   print("It is not present")

Output:

Enter a sentence:I like your scarf
Enter a word to be found in the sentence:car
It is present
>>> 

Some people will say no — "car" is not a word in that sentence — and they would judge your code as incorrect.

For this, use:

a = input("Enter a sentence:")
w = input ("Enter a word to be found in the sentence:")
if w.lower() in a.lower().split():
   print("It is present")
else:
   print("It is not present")

output:

Enter a sentence:I like your scarf
Enter a word to be found in the sentence:car
It is not present

Upvotes: 4

DDJ
DDJ

Reputation: 5

This works perfectly. Since the input() treats everything as string, you can even check for special characters or words which have accented letters.

Upvotes: 0

Related Questions