📜  Python|字符串中所有出现的子字符串

📅  最后修改于: 2022-05-13 01:55:17.722000             🧑  作者: Mango

Python|字符串中所有出现的子字符串

很多时候,在处理字符串时,我们在处理子字符串时遇到了问题。这可能包括查找字符串中特定子字符串的所有位置的问题。让我们讨论可以执行此任务的某些方式。

方法#1:使用列表理解+ startswith()
可以使用这两个功能来执行此任务。 startswith函数主要执行获取子字符串的起始索引的任务,列表推导用于遍历整个目标字符串。

# Python3 code to demonstrate working of
# All occurrences of substring in string
# Using list comprehension + startswith()
  
# initializing string 
test_str = "GeeksforGeeks is best for Geeks"
  
# initializing substring
test_sub = "Geeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# printing substring 
print("The substring to find : " + test_sub)
  
# using list comprehension + startswith()
# All occurrences of substring in string 
res = [i for i in range(len(test_str)) if test_str.startswith(test_sub, i)]
  
# printing result 
print("The start indices of the substrings are : " + str(res))
输出 :
The original string is : GeeksforGeeks is best for Geeks
The substring to find : Geeks
The start indices of the substrings are : [0, 8, 26]

方法 #2:使用re.finditer()
正则表达式库的 finditer函数可以帮助我们执行在目标字符串中查找子字符串出现的任务,并且 start函数可以返回每个子字符串的结果索引。

# Python3 code to demonstrate working of
# All occurrences of substring in string
# Using re.finditer()
import re
  
# initializing string 
test_str = "GeeksforGeeks is best for Geeks"
  
# initializing substring
test_sub = "Geeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# printing substring 
print("The substring to find : " + test_sub)
  
# using re.finditer()
# All occurrences of substring in string 
res = [i.start() for i in re.finditer(test_sub, test_str)]
  
# printing result 
print("The start indices of the substrings are : " + str(res))
输出 :
The original string is : GeeksforGeeks is best for Geeks
The substring to find : Geeks
The start indices of the substrings are : [0, 8, 26]