在Python字串中查詢所有子字串出現的位置


字串由字元組成,在程式碼中使用單引號或雙引號初始化,子字串也是字串中存在的字元。Python是一種用途廣泛的高階語言,使用者易於理解。本文介紹了使用Python語言查詢字串中所有子字串出現位置的各種方法。一些常用方法包括index()方法、in運算子、find()方法以及使用正則表示式方法。

在Python字串中查詢所有子字串出現的位置

子字串是字串的字元,下面解釋了查詢這些子字串的方法。

語法

str.find(substr, initial, final)

使用find()函式給出要搜尋的字串str。此函式具有三個引數:子字串、字串的初始值(為0)以及最終值(可以根據字串的長度而定)。

方法

方法1 - 使用try和except方法

方法2 - 使用“re”正則表示式

方法1:使用try和except方法列印子字串所有出現位置的Python程式

初始化輸入字串,使用index()方法迭代每個未找到的子字串,引發ValueError,並在except塊中列印語句。

演算法

  • 步驟1 - 將變數定義為“Hello Welcome to Tutorialspoint”。

  • 步驟2 - 將子字串變數定義為“l”、“z”和“e”。

  • 步驟3 - 使用index()方法查詢從初始索引開始的字串中子字串的第一次出現。

  • 步驟4 - 使用for迴圈迭代字串,當子字串存在於字串中時,列印“所有字串都找到”語句。

  • 步驟5 - 當子字串不存在於字串中時,列印“並非所有字串都找到”語句。

  • 步驟6 - 使用try和except方法,檢查字串中子字串的所有可能出現位置。

  • 步驟7 - 執行以下程式碼時,將返回輸出。

示例

#initializing the string
num = "Hello welcome to India" 

#to find the occurrence of the substring ‘l’, ‘z’, ‘e’ is initialized as substr
substr = ["l", "z", "e"] 
#trying to find the substrings using index() method
try:
   for sub in substr:
      num.index(sub)
   #this statement is printed when the substring is present in the input string
   print("All substrings found!") 
except ValueError:
   #this statement is printed when the substring is not present in the input string
   print("substrings are not found!") 

輸出

substrings are not found!

方法2:使用“re”正則表示式列印子字串所有出現位置的Python程式

建立正則表示式模式以將所有子字串列表與輸入字串匹配。然後,使用re Python庫中的findall()函式查詢字串的所有出現位置。如果匹配次數等於子字串列表的長度,則此表示式返回true,否則返回false。

演算法

  • 步驟1 - 匯入所需的模組作為“re”庫,並定義名為all_substrings_present()的函式。

  • 步驟2 - 使用已匯入的“re”庫使用findall()函式檢查子字串。

  • 步驟3 - 當子字串與字串匹配時,定義的函式返回“true”,否則返回“false”。

  • 步驟4 - 將名為input_str的字串初始化為“Hello welcome to India”,其中包含一組字串,並在下一條語句中初始化子字串。

  • 步驟5 - 使用if-else語句驗證子字串是否存在於input_str中。

  • 步驟6 - 最後,根據條件返回列印語句。

示例

#importing the “re” module
import re
#defining the function with two parameters as input string and substring
def strfind(input_str, substr_list):
   # Regular expression is created and initialized as a shape
   shape = "(?=.*" + ")(?=.*".join(substr_list) + ").*"
   #using the findall() function to check for the characters in the string
   matches = re.findall(shape, input_str)

   # when the substrings are matched with the strings it returns true else false
   return len(matches) == 1
#initializing the string 
input_str = "Hello welcome to India"
#initializing the characters that need to be found in the input string
substr_list = ["l", "c", "e"]

#To check using the if else statement 
if strfind(input_str, substr_list):
#when the characters are matched this statement is printed.
   print("All substrings found!")
else:
#when the characters are not matched this statement is printed.
   print("Not all substrings found.")

輸出

All substrings found!

結論

程式設計師可以處理字串,但是處理子字串會導致一些複雜的問題。透過使用各種方法,我們可以找到給定輸入字元字串中子字串的所有出現位置。輸出根據字串值的匹配返回。

更新於:2023年8月25日

4K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告