Python 查找字符串中的所有子串

Document 对象参考手册 Python3 实例

在 Python 中,我们可以使用字符串的 find() 方法或者正则表达式来查找字符串中的所有子串。下面是一个使用 find() 方法的示例代码:

实例

def find_all_substrings(main_string, sub_string):
    start = 0
    positions = []
    while True:
        start = main_string.find(sub_string, start)
        if start == -1:
            break
        positions.append(start)
        start += 1
    return positions

main_string = "hello world, hello python, hello programming"
sub_string = "hello"
positions = find_all_substrings(main_string, sub_string)
print(positions)

代码解析:

  1. find_all_substrings 函数接受两个参数:main_string 是主字符串,sub_string 是要查找的子串。
  2. start 变量用于记录查找的起始位置,初始值为 0。
  3. positions 列表用于存储所有找到的子串的起始位置。
  4. while True 循环会一直进行,直到 find() 方法返回 -1,表示没有找到更多的子串。
  5. main_string.find(sub_string, start)start 位置开始查找子串 sub_string,返回子串的起始位置。如果找不到,返回 -1。
  6. 如果找到子串,将其起始位置添加到 positions 列表中,并将 start 增加 1,以便继续查找下一个子串。
  7. 最后返回 positions 列表,其中包含所有子串的起始位置。

输出结果:

[0, 13, 26]

在这个例子中,子串 "hello" 在主字符串中出现了三次,起始位置分别是 0、13 和 26。

Document 对象参考手册 Python3 实例