python在字符串中发生的字母。指数计数

时间:2014-04-09 09:51:08

标签: python

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

下面是写的功能。它只打印出我给出的第一个索引

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

以上是我需要的功能类型。我无法弄清楚缺少什么。

3 个答案:

答案 0 :(得分:3)

您不应该直接返回索引,因为它终止了该功能。而是按如下方式进行:

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')
[]

答案 1 :(得分:0)

试试这个,

>>> 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]

答案 2 :(得分:0)

我愿意:

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

演示:

>>> list(ind_find('apollo', 'o'))
[2, 5]

您的代码无法正常工作的原因是您找到第一个索引后return。我的代码通过构造所有索引的list来解决这个问题,然后在适用的时候返回它。