如何在 Python 中檢查多個字串是否存在於另一個字串中?


在本文中,我們將瞭解如何在 Python 中檢查多個字串是否存在於另一個字串中。

想象一下,我們需要滿足 50 個要求才能完成一項工作。為了檢查條件是否為真,我們通常使用條件語句(if、if-else、elif、巢狀 if)。但是,對於如此多的條件,由於過度使用 if 語句,程式碼會變得很長且難以閱讀。

在這樣的情況下,Python 的any() 函式是唯一的選擇,因此程式設計師必須使用它。

第一種方法是編寫一個函式來檢查多個字串是否存在,然後使用 'any' 函式檢查是否有任何情況為真,如果任何情況為真,則返回 True,否則返回 False。

示例 1

在下面給出的示例中,我們獲取一個字串作為輸入,並使用any() 函式檢查是否存在與匹配字串的任何匹配項。

match = ['a','b','c','d','e']
str = "Welcome to Tutorialspoint"

print("The given string is")
print(str)

print("Checking if the string contains the given strings")
print(match)

if any(c in str for c in match):
   print("True")
else:
   print("False")

輸出

上面示例的輸出如下所示:

The given string is
Welcome to Tutorialspoint
Checking if the string contains the given strings
['a', 'b', 'c', 'd', 'e'] 15. 
True

示例 2

在下面給出的示例中,我們採用與上面相同的程式,但使用不同的字串進行檢查。

match = ['a','b','c','d','e']
str = "zxvnmfg"

print("The given string is")
print(str)

print("Checking if the string contains the given strings")
print(match)

if any(c in str for c in match):
   print("True")
else:
   print("False") 

輸出

上面示例的輸出如下所示:

The given string is
zxvnmfg
Checking if the string contains the given strings
['a', 'b', 'c', 'd', 'e']
False

使用正則表示式

第二種方法使用正則表示式。要使用它,請匯入 re 庫,如果尚未安裝,請安裝它。載入 re 庫後,我們將使用 Regex 和re.findall() 函式來檢查另一個字串中是否存在任何字串。

示例 1

在下面給出的示例中,我們獲取一個字串作為輸入和多個字串,並使用正則表示式檢查多個字串中的任何一個是否與該字串匹配。

import re
match = ['a','b','c','d','e']
str = "Welcome to Tutorialspoint"

print("The given string is")
print(str)

print("Checking if the string contains the given strings")
print(match)

if any(re.findall('|'.join(match), str)):
   print("True")
else:
   print("False")

輸出

上面示例的輸出如下所示:

The given string is
Welcome to Tutorialspoint
Checking if the string contains the given strings
['a', 'b', 'c', 'd', 'e']
True

示例 2

在下面給出的示例中,我們採用與上面相同的程式,但使用不同的字串進行檢查。

import re
match = ['a','b','c','d','e']
str = "zxvnmfg"

print("The given string is")
print(str)

print("Checking if the string contains the given strings")
print(match)

if any(re.findall('|'.join(match), str)):
   print("True")
else:
   print("False")

輸出

上面示例的輸出如下所示:

The given string is
zxvnmfg
Checking if the string contains the given strings
['a', 'b', 'c', 'd', 'e']
False

更新於: 2022-12-07

8K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.