如何查找所有出现的子字符串?Pythonstring.find()和string.rfind()若要获取字符串中的子字符串的索引,请执行以下操作。我想知道是否有string.find_all()它可以返回所有找到的索引(不仅从开始返回第一个索引,或者从末尾返回第一个索引)。例如:string = "test test test test"print string.find('test') # 0print string.rfind('test') # 15#this is the goalprint string.find_all('test')
# [0,5,10,15]
5 回答
汪汪一只猫
TA贡献1898条经验 获得超8个赞
import re[m.start() for m in re.finditer('test', 'test test test test')]#[0, 5, 10, 15]
[m.start() for m in re.finditer('(?=tt)', 'ttt')]#[0, 1]
search = 'tt'[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]#[1]
re.finditer
[]
()
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
>>> help(str.find)Help on method_descriptor:find(...) S.find(sub [,start [,end]]) -> int
def find_all(a_str, sub): start = 0 while True: start = a_str.find(sub, start) if start == -1: return yield start start += len(sub) # use start += 1 to find overlapping matcheslist(find_all('spam spam spam spam', 'spam')) # [0, 5, 10, 15]
添加回答
举报
0/150
提交
取消