[英]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
。 在這種情況下, idx
為0
現在我們將檢查 '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.