只是尝试编写一个基本函数,该函数应该打印单词中某个字母的索引号。
下面是函数的编写。它只打印出我给出的字母的第一个索引
def ind_fnd(word, char):
"""
>>> ind_fnd("apollo", "o")
'2 5 '
>>> ind_fnd("apollo", "l")
'3 4 '
>>> ind_fnd("apollo", "n")
''
>>> ind_fnd("apollo", "a")
'0'
"""
index = 0
while index < len(word):
if word [index] == char:
return index
index += 1
以上是我需要的功能类型。我无法弄清楚缺少什么。
最佳答案
您不应该立即返回索引,因为这会终止函数。相反,请按如下方式操作:
def ind_fnd(word, char):
"""
>>> ind_fnd("apollo", "o")
'2 5 '
>>> ind_fnd("apollo", "l")
'3 4 '
>>> ind_fnd("apollo", "n")
''
>>> ind_fnd("apollo", "a")
'0'
"""
index = 0
indices = []
while index < len(word):
if word [index] == char:
indices.append(index)
index += 1
return indices
这将创建所有索引的列表,然后返回它。
示例
>>> ind_fnd('apollo','o')
[2,5]
>>> ind_fnd('eevee','e')
[0,1,3,4]
>>> ind_fnd('hello, 'z')
[]
关于python 字符串中出现的字母。索引计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22958839/