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'))
Advertisement
Answer
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:
A listcomp with
enumerate
:JavaScript121allindices = [i for i, x in enumerate(a) if x == 'o']
2
A loop that calls
index
with an explicitstart
argument:JavaScript181idx = -1 # -1 means first search will begin at beginning of string
2try:
3while True:
4idx = a.index('o', idx + 1) # Resume search after last index found
5print(idx)
6except ValueError:
7pass # Ran out of 'o's, we're done
8
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.