如何在 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.