简体   繁体   中英

How to get position of each character on a string without using find function

I want this function to return the position of each occurrence of a specific character in a given string without using the find function.

The code only returns the first instance, but not the rest of them. I could use append, but I'm not sure on how to use it. This is what I've tried so far:

#eg: find("Pythhon","h")
#needed output: [3,4] (the positions of each occurrence)
#instead the output is showing: [3] (position) 
def find(string, token):
    #start at index 0
    for e in range(0,len(string)):
        #compare each character to token
        if string[e] == token:
            #if true return the position of occurences
            return [e]

Your code it's basically right. The problem is that you're just saying in your code that, if the coincidence is found between the string and the token, then return the position e , finishing there the for loop.

Thus, to avoid your problem, you only need to add an empty string at the begining of your function ( result = [] ) and, when a coincidence is found, append this position to the result list. Finally, once the for loop is finished, ask your function to return result

This should work:

#eg: find("Pythhon","h")
#needed output: [3,4] (the positions of each occurrence)
#instead the output is showing: [3] (position) 
def find(string, token):
    #start at index 0
    result = []
    for e in range(0,len(string)):
        #compare each character to token
        if string[e] == token:
            #if true return the position of occurences
            result.append(e)
    return result

Above the for loop, put occurrences=[] - you need a list to append to, so this defines an empty list.

Then instead of return[e] you want occurences.append(e) , this adds e to the list. Return will end the function immediately without completing the loop, and output the value you return

And right at the bottom, after the for loop completes, return occurrences - that way, you return the complete list of indexes rather than the index of the first element that matches.

Another way to do that is:

def find(string, char):
    return [i for i, c in enumerate(string) if char == c]

>>> find("Pythhon", "h")
[3, 4]

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