Skip to main content
 首页 » 编程设计

python之如何检查两个给定单词之间是否不存在字符串

2025年05月04日15sxdcgaq8080

我需要检查给定的任意两个单词,它们之间是否存在字符串或什么都没有。

例如我有一个句子 Hey how are you?。在此我需要检查两个单词 Hey 和 how 之间是否存在任何字符串。这是我目前所做的

s = "hey how are you?" 
substring1 = 'hey' 
substring2 = 'how' 
my_string = s[(s.index(substring1)+len(substring1)):s.index(substring2)] 
if " " in my_string: 
    print("no string found!") 

在这里,我选择两个词之间的任何内容,并检查它是否为空白。它似乎有效,但有一个问题。如果我在两者之间添加一个字符串并在其周围放置空格,例如 "hey there how are you?",它仍然说找不到字符串。

我需要确定如果两个词之间绝对没有任何东西存在,那么我才会输出消息。我该怎么做?

请您参考如下方法:

如果单词之间只允许有空格,您可以按空格拆分并检查 "hey" 和 "end" 的索引是否连续:

s = "hey how are you?" 
 
start = "hey" 
end = "how" 
 
words = s.split() 
 
if abs(words.index(end) - words.index(start)) > 1: 
    print("something") 
else: 
    print("nothing") 

输出

nothing