0

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]
1
  • Hi @user15344675! Please check out my answer and if it's what you were looking for, please, consider accepting it as the correct one – marsolmos Mar 20 at 18:26
6

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
1
  • 1
    Thanks for the info @PranavHosangadi. I will edit it to give some more clarification on the code itself! – marsolmos Mar 17 at 21:57
3

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.

2
0

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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.