在字符串中出现字母的python。指数计数

在字符串中出现字母的python。指数计数,python,Python,只是试着写一个基本函数,函数应该打印单词中某个字母的索引号 下面是编写的函数。它只是打印出我给你的信的第一个索引a def ind_fnd(word, char): """ >>> ind_fnd("apollo", "o") '2 5 ' >>> ind_fnd("apollo", "l") '3 4 ' >>> ind_fnd("apollo", "n") '' >&g

只是试着写一个基本函数,函数应该打印单词中某个字母的索引号

下面是编写的函数。它只是打印出我给你的信的第一个索引a

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
定义索引(字、字符): """ >>>ind_fnd(“阿波罗”,“o”) '2 5 ' >>>ind_fnd(“阿波罗”,“l”) '3 4 ' >>>ind_fnd(“阿波罗”,“n”) '' >>>印度(“阿波罗”,“a”) '0' """ 索引=0 而索引
以上是我需要的函数类型。我不知道缺少了什么。

您不应该立即返回索引,因为这样会终止函数。相反,请按如下方式执行:

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
试试这个

>>> def find(word,char):
          result=[]
          for index,i in enumerate(word):
            if i==char:
               result.append(index)
          return result

>>> print find("this is example string",'i')
[2, 5, 19]
我会:

def ind_find(s, c):
    return (i for i, x in enumerate(s) if x == c)
演示:

代码不起作用的原因是,一旦找到第一个索引,就返回
。我的代码通过构造一个包含所有索引的
列表
来解决这个问题,然后在适用时返回该列表

def ind_find(s, c):
    return (i for i, x in enumerate(s) if x == c)
>>> list(ind_find('apollo', 'o'))
[2, 5]