0
message = "I'm new and this is new my account."

The program will try to detect 'hi' in this string even there is no 'hi' in here, it will found the keyword in "and this is m..." part if try to use a code like this:

if "hi" in message.lower():
    print("He said hi!")

How can I block this out?

Demir
  • 13
  • 5

2 Answers2

3

You can use regular expressions.

import re


message = "I'm new and this is new my account."
message_with_hi = "what's up, I'm saying hi"
pattern = r'\bhi\b'  # \b is word boundary

r = re.findall(pattern, message)
r2 = re.findall(pattern, message_with_hi)
print(r)  # prints []
print(r2)  # prints ['hi']

This also covers cases like message = "I am saying hi!".

bananafish
  • 2,877
  • 20
  • 29
-1

An elegant solution would be:

if ' hi ' in f' {message} ':
    print("He said hi!")

Or using regex: https://stackoverflow.com/a/5320179/4585157

Dolev Pearl
  • 264
  • 2
  • 8
  • it can be work but what if the string starts with hi? "hi, my name is ..." yes, there's a space after 'hi' but no space before 'hi' – Demir Dec 21 '20 at 21:52
  • @Demir Use [this answer](https://stackoverflow.com/a/65400389/2415524) to handle that case. – mbomb007 Dec 21 '20 at 21:52
  • @Demir then this would still work. We add a space before and after the message for the check. – Dolev Pearl Dec 21 '20 at 21:55