Reputation: 6522
I'm a complete beginner in Python and I'm trying to find Indexes for every "o" in this string. This only shows index for first o, while I'm trying to find all of them:
besedilo = "Dober dan Slovenija"
print (besedilo.index("o"))
I thought I could use for loop but I'm not quite sure how to do it
Upvotes: 0
Views: 122
Reputation: 1124748
Use a list comprehension with enumerate()
:
indices = [i for i, c in enumerate(besedilo) if c == 'o']
Demo:
>>> besedilo = "Dober dan Slovenija"
>>> [i for i, c in enumerate(besedilo) if c == 'o']
[1, 12]
The str.index()
method also takes an optional start
argument, the starting index from which to search (defaults to 0), so you could build a loop with the last location + 1 to collect all indices:
indices = []
next = -1
while True:
try:
next = besedilo.index(next + 1)
indices.append(next)
except ValueError:
break
If speed is an issue, then this last method is actually the faster option of the two:
$ bin/python -m timeit -s "test = 'Dober dan Slovenija'" "indices = [i for i, c in enumerate(test) if c=='o']"
100000 loops, best of 3: 2.51 usec per loop
$ bin/python -m timeit -s "test = 'Dober dan Slovenija'" -s "indices,next=[],-1" "while True:" " try:" " next= test.index('o', next+1)" " indices.append(next)" " except ValueError: break"
1000000 loops, best of 3: 1.06 usec per loop
Upvotes: 2
Reputation: 60024
Use enumerate()
:
>>> besedilo = "Dober dan Slovenija"
>>> [i for i, j in enumerate(besedilo) if j == 'o']
[1, 12]
This will loop through both the string and a sort of counter starting from 0. If a letter matches 'o'
, then the count will be in the list returned by the list comprehension.
Alternatively, you can use the itertools
module:
>>> import itertools
>>> [i for i, j in itertools.izip(itertools.count(), besedilo) if j == 'o'] # itertools.izip not needed if you are using Python 3
[1, 12]
Keep in mind that enumerate()
is much more efficient :).
Upvotes: 2