简体   繁体   中英

Find indexes for a certain character in string

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

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 :).

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

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