首页 > 解决方案 > 检查多个字符串是否连续存在于另一个字符串中

问题描述

如何检查数组中的任何字符串是否存在于另一个字符串中?

喜欢:

a = ['the', 'you']
b = ['is', 'are']
c = ['now', 'not']
str = "the game is now"
if "the" in str:
 print "the strings found in str"
else:
 print "the strings found in str"

现在我想检查是否在“a”中找到“you”,然后在“b”中找到“are”,而不是在此之前。任何帮助,请亲爱的?

标签: pythonpython-2.7

解决方案


可以使用正则表达式来做到这一点。

import re

a = ['your', 'game', "is", "over"]
regex = ".+".join(a)
print(regex)
if re.match(regex, "your game my dear player is over"):
    print("It's over")

带索引:

a = ['your', 'game', "is", "over"]

list_of_words = " game my dear player is over".split()
is_correct = True
for i, value in enumerate(a):
    if i < 1:
        continue
    if value not in list_of_words or a[i - 1] not in list_of_words:
        is_correct = False
        break
    if list_of_words.index(value) < list_of_words.index(a[i - 1]):
        is_correct = False
if is_correct:
    print("It's over")

推荐阅读