📌  相关文章
📜  Python|获取给定子字符串的所有出现的起始索引

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

Python|获取给定子字符串的所有出现的起始索引

给定一个字符串和一个子字符串,找出字符串中所有给定子字符串出现的起始索引的任务。让我们讨论一些解决给定任务的方法。

方法#1:使用朴素方法

# Python3 code to demonstrate
# to find all occurrences of substring in
# a string
  
# Initialising string
ini_string = 'xbzefdgstbzefzexezef'
  
# Initialising sub-string
sub_string = 'zef'
  
# Printing initial string and sub-string
print ("initial_strings : ", ini_string, "\nsubstring : ", sub_string)
  
res = []
flag = 0
k = 0
  
# Finding all occurrences of substring
# in a string using Naive method
for i in range(0, len(ini_string)):
    k = i
    flag = 0
    for j in range(0, len(sub_string)):
        if ini_string[k] != sub_string[j]:
            flag = 1
        if flag:
            break
        k = k + 1
    if flag == 0:
        res.append(i)
  
  
# printing result(
print ("resultant positions", str(res))
输出:
initial_strings :  xbzefdgstbzefzexezef 
substring :  zef
resultant positions [2, 10, 17]

&nsbp;
方法 #2:使用列表推导

# Python3 code to demonstrate
# to find all occurrences of substring in
# a string
  
# Initialising string
ini_string = 'xbzefdgstbzefzexezef'
  
# Initialising sub-string
sub_string = 'zef'
  
# Printing initial string and sub-string
print ("initial_strings : ", ini_string, "\nsubstring : ", sub_string)
  
res = []
# Finding all occurrences of substring
# in a string using list comprehension
res = [i for i in range(len(ini_string)) 
       if ini_string.startswith(sub_string, i)]
  
# printing result(
print ("resultant positions", str(res))
输出:
initial_strings :  xbzefdgstbzefzexezef 
substring :  zef
resultant positions [2, 10, 17]


方法#3:使用正则表达式

# Python3 code to demonstrate
# to find all occurrences of substring in
# a string
import re
  
# Initialising string
ini_string = 'xbzefdgstbzefzexezef'
  
# Initialising sub-string
sub_string = 'zef'
  
# Printing initial string and sub-string
print ("initial_strings : ", ini_string, "\nsubstring : ", sub_string)
  
res = []
# Finding all occurrences of substring
# in a string using re.finditer
res = [m.start() for m in re.finditer(sub_string, ini_string)]
  
# printing result(
print ("resultant positions", str(res))
输出:
initial_strings :  xbzefdgstbzefzexezef 
substring :  zef
resultant positions [2, 10, 17]