获取字符串中子字符串的所有第一个和最后一个索引对的最佳方法是什么?
例如,如果我的字符串是" abcdegf",则子字符串" bcd"是[1:4]。
这个功能让我得到答案,但如果没有更优雅的解决方案,我会感到惊讶。
>>> 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)]
答案 0 :(得分:3)
您可以利用正则表达式,match.start()
将返回他的起始位置,match.end()
将提供结束位置(搜索是文字字符串,因此它必须是re.escape
d):
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)])
请参阅Python demo
答案 1 :(得分:2)
这样的事可能吗?
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 :支持多个子字符串出现。