天天看點

Python3 傳回string中某元素所有的index

str.index(sub[, start[, end]] ) 隻能傳回範圍内的第一次出現該元素的index,但有的時候我們想要傳回string内此元素所有的index,可以這樣做      
find_all = lambda c, s: [x for x in range(c.find(s), len(c)) if c[x] == s]
S = 'loveleetcode'
C = 'e'
index_all = find_all(S, C) # [3, 5, 6, 11]
           

還有一種做法是用正規表達式來做:

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('e', 'loveleetcode')]
#[3, 5, 6, 11]
           
參考:https://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python