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的起始位置和终止位置。 |
|