今天小编跟大家分享一下,如何从一个字符串中找到所有匹配的子字符串的位置。例如我们有下面这一句话,我们需要从中找到所有‘you’出现的位置。
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的起始位置和终止位置。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有