繁体   English   中英

如何检查 Python 中列表的另一个字符串是否跟在一个字符串后面?

[英]How can I check if a string is followed by another string of a list in Python?

我尝试了以下方法:

if "a string" or "a string 2" in comment, any(string in comment for string in list)

逗号应该是“后跟”之类的东西

考虑:

comment = 'How can I check if a string is followed by another string'

并且您想检查“如何”后跟以下列表中的单词之一

check_list = ['can', 'string', 'followed']

然后您可以先将comment拆分为单词列表

comment_words = comment.split(' ')

list带有一个名为index的方法来告诉我们特定元素在哪里,但如果它不存在,它将引发ValueError ,所以我会在try块中使用它来捕获错误。

try:
    idx = comment_words.index('How') #note that it is case-sensitive
    # should return a `0` to `idx`
except:
    idx = None

因此,如果 'How' 在单词中, idx将是一个数字,否则,它将是None 在这种情况下, idx0

现在我们将检查 'How' 后面是否跟check_list中的单词之一

if (idx is not None) and\
    (idx + 1 < len(comment_words)) and\
    comment_words[idx+1] in check_list:
    print('How is in the comment, and is followed by one of the words in the check list')

请注意,我们有 3 个条件要检查,并且因为它们与and进行比较,所以只有在前一个条件被评估为True时才会检查后面的条件。 在这种情况下,肯定的第一个条件确保找到 'How',肯定的第二个条件确保 'How' 不是最后一个单词,而肯定的第三个条件告诉我们下一个单词是check_list中的一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM