Reputation: 31
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]
Upvotes: 0
Views: 711
Reputation: 95921
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]
Upvotes: 0
Reputation: 794
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
Upvotes: 6
Reputation: 108
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.
Upvotes: 3