分享

Python字符串操作--寻找所有匹配的位置

 生信交流平台 2021-12-29

You said I was your life. Are you still alive when you lost it?

下面给出两种方法

1. 使用find函数来实现

def find_all(string, sub): start = 0 pos = [] while True: start = string.find(sub, start) if start == -1: return pos pos.append(start) start += len(sub)

print(find_all('You said I was your life. Are you still alive when you lost it?', 'y'))

string里面存了完整的字符串,find函数有两个参数,第一个参数sub,是需要寻找的子字符串,start是从string的什么地方开始寻找sub。找到之后将位置信息保存到pos中。然后start往后移动一个sub的长度,开始寻找第二个匹配的位置,一直到返回-1,证明找不到了,就返回pos,里面保存了所有sub的位置信息。

2.使用re包来实现

import re
string = 'You said I was your life. Are you still alive when you lost it?'pattern = 'you'for m in re.finditer(pattern, string): print(m.start(), m.end())

直接通过循环来实现,然后返回找到的pattern的起始位置和终止位置。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多