有没有一种方法可以从python中的字符串中找到关键字

2024-04-20 11:57:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

程序将尝试检测此字符串中的“hi”,即使此处没有“hi”,如果尝试使用以下代码,它将在“和this is m…”部分找到关键字:

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

我怎样才能把它屏蔽掉


3条回答

您可以使用正则表达式

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']

这也包括message = "I am saying hi!"等情况

一个优雅的解决方案是:

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

或者使用正则表达式:https://stackoverflow.com/a/5320179/4585157

你也可以试试这个,但我想第一个答案更好

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

相关问题 更多 >