-1

I have a string. The letter 'o' appears twice in the whole string, but when I try to use the index() function to locate the position where the 'o' appears, it just traverses from left to right and stops when it finds the first 'o'.

Why can't index() print all the locations of 'o'?

If possible, how can I use index() to print all the strings that meet the conditions?

a = 'HaloPython!'
print(a.index('o'))
J0hn
  • 63
  • 7
  • The index() method returns the position at the first occurrence of the specified value. – Nesi Aug 01 '22 at 23:23
  • 1
    read the documentation of the python string index function ... the answer is there – jsotola Aug 01 '22 at 23:24
  • 2
    Does this answer your question? [How to find all occurrences of a substring?](https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring) – Nesi Aug 01 '22 at 23:24
  • I don't think this question is a duplicate of this one [How to find all occurrences of a substring?](https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring). This question is more about whether index() can return all contained strings. So I think this is a separate question. Obviously, index() can only return the first value. Thank you very much. – J0hn Aug 02 '22 at 21:21

1 Answers1

1

index returns exactly one index per call. It's not going to try to shove all indices into the result, changing return type based on the values.

Two obvious ways to handle it:

  1. A listcomp with enumerate:

    allindices = [i for i, x in enumerate(a) if x == 'o']
    
  2. A loop that calls index with an explicit start argument:

    idx = -1  # -1 means first search will begin at beginning of string
    try:
        while True:
            idx = a.index('o', idx + 1)  # Resume search after last index found
            print(idx)
    except ValueError:
        pass  # Ran out of 'o's, we're done
    

The listcomp solution is by far the most common and obvious solution (and can be made to work for length > 1 substrings by using start modified calls to str.startswith), but if you must use index to do it, option #2 exists.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271