如何修改Python代码以获取字符串中子串所有字符的索引?
解决子串所有字符索引的输出问题
没问题,我来帮你调整代码实现需求!
你原来的代码里,s.index(duplicate)只会返回子串第一个字符的起始位置,所以只输出了6。要拿到子串所有字符的索引,我们可以从这个起始位置出发,根据子串的长度生成连续的索引序列。
基础实现(处理单次匹配)
如果你的目标子串在字符串里只出现一次,直接这样修改就行:
dup = ["aaa","bbb","ccc"] s = "hfidgfaaahjfihdfhd" for duplicate in dup: if duplicate in s: start_idx = s.index(duplicate) # 生成子串所有字符的索引:从start_idx开始,共len(duplicate)个连续整数 for idx in range(start_idx, start_idx + len(duplicate)): print(idx)
运行这段代码后,就会依次输出6、7、8,正好对应"aaa"三个字符在s中的位置。
进阶实现(处理多次匹配)
如果字符串里可能存在多个相同的子串(比如s是"hfidgfaaahjfihdfhdaaa"),上面的代码只会处理第一个匹配项。这时候可以用find()结合循环,找出所有匹配的起始位置,再生成对应索引:
dup = ["aaa","bbb","ccc"] s = "hfidgfaaahjfihdfhdaaa" for duplicate in dup: start_pos = 0 # 循环查找所有匹配的起始位置 while True: start_idx = s.find(duplicate, start_pos) if start_idx == -1: # 找不到匹配时退出循环 break # 输出当前匹配的所有字符索引 char_indices = list(range(start_idx, start_idx + len(duplicate))) print(f"子串'{duplicate}'的字符索引:{char_indices}") # 移动起始位置,避免重复匹配同一个子串 start_pos = start_idx + 1
这段代码会输出两次[6, 7, 8]和[17, 18, 19],覆盖所有匹配的子串字符索引。
内容的提问来源于stack exchange,提问作者patrick chong
相关产品推荐
相关产品推荐

