Skip to main content
 首页 » 编程设计

python之按特定顺序测试多个字符串

2025年05月04日19cmt

有没有办法按特定顺序测试多个字符串?像这样:

if str.find(["who", "are", "you"], "who the heck are you") != -1: 
    Print("I AM JOE") 

请您参考如下方法:

逐字测试,检查每个关键字是否包含在前一个关键字之后。

def find_in_order(text, words): 
    tokens = text.split() 
    start = 0 
    for word in words: 
        try: 
            start = tokens.index(word, start) + 1 
        except: 
            return False 
    return True 

测试:

>>> find_in_order("who the hell are you", ["who", "are", "you"]) 
True 
>>> find_in_order("who the hell is you", ["who", "are", "you"]) 
False 
>>> find_in_order("you who the hell are you", ["who", "are", "you"]) 
True 
>>> find_in_order("who bare bayou", ["who", "are", "you"]) 
False 
>>> find_in_order("who are you", ["who", "are", "are", "you"]) 
False 

或者使用不在空格处拆分的变体,因此 who bare byou 将通过:

def find_in_order(text, words): 
    start = 0 
    for word in words: 
        try: 
            start = text.index(word, start) + len(word) 
        except: 
            return False 
    return True