简体   繁体   中英

Checking if index in a string is a certain letter

I want to make a list, that contains indices, that tell me where in a string a certain character is.

So far i have this:

def function(string):
    a = []
    for i in string:
        if string[i] == '*':
           a.append(i)

and i get an error: string indices must be integers.

I searched how to fix this, but couldn't find any suitable answers.

So remember that when you loop over an iterator the value of i takes on each element in the iterable.

So if we had:

for i in "Hello":
     print(i)

Then we would get "H", "e", "l", "l", "o".

These strings cannot be used to index a string. Instead compare i directly with *

def function(string):
    a = []
    for index, character in enumerate(string):
        if character == '*':
           a.append(index)

The enumerate function counts each iteration

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