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'))
CodePudding user response:
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
:allindices = [i for i, x in enumerate(a) if x == 'o']
A loop that calls
index
with an explicitstart
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.