简体   繁体   中英

First and Second occurrence in string Python

I have an inputted string that may contain letter 'f'. If the word contains no fs, print -1; if there's only one f in the word, print its index; if it occurs twice or more times, print the indexes of two first occurrences.

For example if we have the word office the output should be --> 1 2

I have tried:

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)

Call str.index() with the offset + length of the previous match as the start index to find the next occurrence of a substring:

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'))

Which prints [1, 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM