如何在不使用find函数的情况下获取字符串上每个字符的位置
我希望这个函数在不使用 find 函数的情况下返回给定字符串中特定字符每次出现的位置。
代码只返回第一个实例,而不返回其余的实例。我可以使用 append,但我不确定如何使用它。这是我迄今为止尝试过的:
#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]
回答
你的代码基本上是对的。问题是您只是在代码中说,如果在字符串和标记之间发现重合,则返回 position e,在那里完成for循环。
因此,为了避免您的问题,您只需在函数 ( result = [])的开头添加一个空字符串,并在发现巧合时将此位置附加到结果列表中。最后,一旦 for 循环完成,请让您的函数return result
这应该有效:
#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