[英]How can I slice a string from the index of the first occurrence of a sub string to the second occurrence of a sub string in Python?
[英]First and Second occurrence in string Python
我有一個可能包含字母“f”的輸入字符串。 如果單詞不包含 fs,則打印 -1; 如果單詞中只有一個 f,則打印它的索引; 如果它出現兩次或更多次,則打印兩次第一次出現的索引。
例如,如果我們有單詞 office output 應該是 --> 1 2
我努力了:
if s.find('f') > 0:
if s.find('f').count() >= 2:
print(s.find('f'))
if s.find('f').count() == 1:
print(s.find('f'))
else:
print(-1)
調用str.index()
並將前一個匹配的偏移量 + 長度作為起始索引,以查找下一個出現的 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ:
def find_indices(string_value, term):
indices = []
offset = 0
while offset < len(string_value):
try:
idx = string_value.index(term, offset)
indices.append(idx)
offset = idx + len(term)
except ValueError:
break
return indices
print(find_indices('office', 'f'))
打印[1, 2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.