如何在Python中获取字符串中字符或子串的所有出现位置列表
在Python中获取字符串中字符/子串的所有出现位置列表
方法1:循环调用find()方法
利用str.find(sub, start)可指定起始查找位置的特性,循环查找直到无匹配项,收集所有索引:
def find_all_occurrences(s, sub): positions = [] start = 0 sub_length = len(sub) while True: index = s.find(sub, start) if index == -1: break positions.append(index) # 若需允许重叠匹配(如"aaa"找"aa"要返回[0,1]),则改为 start = index + 1 start = index + sub_length return positions
测试示例:
- 输入:
find_all_occurrences("This is a string", "s")→ 输出:[3,6,10] - 输入:
find_all_occurrences("How do you do?", " ")→ 输出:[3,6,10] - 输入:
find_all_occurrences("Nothing", "a")→ 输出:[]
方法2:列表推导式实现
单个字符场景
直接遍历字符串,收集匹配字符的索引:
def find_all_char_positions(s, char): return [idx for idx, c in enumerate(s) if c == char]
子串场景
通过切片判断每个起始位置的子串是否匹配:
def find_all_sub_positions(s, sub): sub_length = len(sub) max_start = len(s) - sub_length return [idx for idx in range(max_start + 1) if s[idx:idx+sub_length] == sub]
方法3:正则表达式re.finditer()
适合需要复杂匹配规则的场景(如忽略大小写),用re.escape()转义子串中的正则特殊字符:
import re def find_all_regex_positions(s, sub): return [match.start() for match in re.finditer(re.escape(sub), s)]
内容的提问来源于stack exchange,提问作者Anmol Maheshwari
相关产品推荐
相关产品推荐

