python中怎么返回指定查找字符的位置
在一个长string中搜索某个字符串,比如搜索“test”,我用find只能返回第一个查到的位置,但我想看到比如第3次出现test的位置,但find的参数除了搜索文本,只...
在一个长string中搜索某个字符串,比如搜索“test”,我用find只能返回第一个查到的位置,但我想看到比如第3次出现test的位置,但find的参数除了搜索文本,只有start和end,但我不太清楚大概位置,请问有什么其他函数可以指定返回搜多到第几次出现搜索条件的位置,这样的功能吗?
展开
4个回答
推荐于2016-03-12 · 知道合伙人互联网行家
关注
展开全部
Python编程中对字符串进行搜索查找,并返回字符位置,案例代码如下:
# multiple searches of a string for a substring
# using s.find(sub[ ,start[, end]])
#以下面test这段文本为例
text = 'MSKSASPKEPEQLRKLFIGGLSFETTDESLRSAHFESSSYGSAGRRF'
##查找上面文本中的SA字符串
search = 'SA'
start = 0
while True:
index = text.find(search, start)
# if search string not found, find() returns -1
# search is complete, break out of the while loop
if index == -1:
break
print( "%s found at index %d" % (search, index) )
# move to next possible start position
start = index + 1
//运行结果:
#SA found at index 3
#SA found at index 31
#SA found at index 41
展开全部
用re吧
>>> import re
>>> word = "test"
>>> s = "test abcd test 1234 testcase testsuite"
>>> [m.start() for m in re.finditer(word, s)]
[0, 10, 20, 29]
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
>>> def find_pos(str, tobefind):
... L = len(tobefind)
... def xiter():
... for i, c in enumerate(str):
... if c==tobefind[0] and str[i:i+L] == tobefind:
... yield i
... return list(xiter())
...
>>> find_pos('test test tst testa testb', 'test')
[0, 5, 14, 20]
>>>
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
#常规循环版
def findn(cs,ms,n=1):
finalLoc=0
matchLen=len(ms)
for i in range(n):
midLoc=cs.index(ms)
cs=cs[(midLoc+matchLen):]
if i==0:
finalLoc+=midLoc
else:
finalLoc+=midLoc+matchLen
return finalLoc
#递归版
def findn(cs,ms,n=1,loc=0):
if n==1:
return loc+cs.index(ms)
else:
start=cs.index(ms)+len(ms)
return findn(cs[start:],ms,n-1,start+loc)
print findn('abaabbbbbab','a',3)
#生成器版
def findn(cs,ms,loc=0):
nloc=cs.find(ms)
if nloc!=-1:
start=nloc+len(ms)
yield nloc+loc
for i in findn(cs[start:],ms,start+loc):
yield i
print list(findn('aaaababbbabab','ab'))
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询