一个单词的索引号

时间:2014-04-09 04:31:23

标签: string python-2.7

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

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

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 :(得分:1)

来自文档:

  

string.find(s,sub [,start [,end]])

     

返回s中的最低索引   找到子串sub,使得sub完全包含在   S [开始:结束。失败时返回-1。开始和结束的默认值   负值的解释与切片相同。

意味着它会找到第一个实例。

您可以浏览每个角色,看看您所寻找的角色是否存在,而不是使用find()。

伪代码:

foreach a in word:
   if char is a:
      x = x + 1

答案 1 :(得分:0)

>>> def ind_fnd(word, char):
...     places = []
...     for k in range(0, len(word)):
...             if word[k] == char:
...                     places.append(k)
...     return places
... 
>>> ind_fnd("apollo", "o")
[2, 5]
>>>

使用for循环在单词中每个字符循环一次。然后检查k处的字符是否是您要查找的字符。如果是,请将其添加到places。最后,返回places

或者,正如@wwii所说,你可以使用enumerate(),因为:

>>> def ind_fnd(word, char):
...     places = []
...     for index, c in enumerate(word):
...             if c == char:
...                     places.append(index)
...     return places
... 
>>> ind_fnd('apollo', 'l')
[3, 4]
>>>

答案 2 :(得分:0)

string.find,就像string.index一样,只返回第一个出现的字母。

有一个单行解决方案。

def ind_fnd(word, char)
    return [i for i in range(len(word)) if word[i]==char]