Python获取字符串中所有子字符串出现的索引范围
获取字符串中子字符串的所有第一个和最后一个索引对的最佳方法是什么 例如,如果我的字符串s是“abcdegf”,则子字符串“bcd”是s[1:4] 这个函数给了我答案,但如果没有更优雅的解决方案,我会感到惊讶Python获取字符串中所有子字符串出现的索引范围,python,string,Python,String,获取字符串中子字符串的所有第一个和最后一个索引对的最佳方法是什么 例如,如果我的字符串s是“abcdegf”,则子字符串“bcd”是s[1:4] 这个函数给了我答案,但如果没有更优雅的解决方案,我会感到惊讶 >>> def substring_range(s, substring): for i in range(len(s)-len(substring)): if s[i:i+len(substring)] == substring:
>>> def substring_range(s, substring):
for i in range(len(s)-len(substring)):
if s[i:i+len(substring)] == substring:
yield (i, i+len(substring))
>>> [x for x in substring_range('abcdabcd', 'bc')]
[(1, 3), (5, 7)]
大概是这样吧
control_s, sub_str = "abcdegfbcd", "bcd"
def subs_str_finder(control_s, sub_str):
"""
Finds indexes of all sub_str occurences in control_s.
"""
sub_len = len(sub_str)
while sub_str in control_s:
first_index = control_s.find(sub_str)
second_index = first_index + sub_len
yield first_index, second_index
control_s = control_s.replace(sub_str, "", 1)
for first_index, second_index in subs_str_finder(control_s, sub_str):
print(first_index, second_index)
UPD:支持多个子字符串出现。您可以利用正则表达式,
match.start()
将返回开始位置,match.end()
将提供结束位置(搜索是一个文本字符串,因此必须是re.escape
d):
请参见
“abcdegf.index”(“bcd”)
和“abcdegf.index”(“bcd”)+len(“bcd”)
?str.find
和str.index
都返回子字符串的索引。要获得索引范围,您可以使用一个元组,该索引作为第一个值,索引加上子字符串的长度作为第二个值。这是真的,但我只能找到子字符串的第一个匹配项。我将更新以确保查找所有事件是一个条件。我已使用多个事件支持更新了我的答案。
import re
def substring_range(s, substring):
for i in re.finditer(re.escape(substring), s):
yield (i.start(), i.end())
s = "abcdegfbcd"
substring = "bcd"
print([x for x in substring_range(s, substring)])