python 字符串中出现的字母。索引计数

标签 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

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

最佳答案

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

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/

相关文章:

python - 如何使用 Pandas 创建一个新列来识别时间字段中的接近度?

python - 是否有任何模块允许 Django/Python 与 gnupg 一起工作?

python - Python 中的 SMBus/I2C 在请求读取时不断触发接收回调

python - 如何使用 OpenAI 最大上下文长度为 2049 个 token ?

python - 从装饰器访问 django session

python - 操作错误 : (1045, "Access denied for user ' root' @'localhost'(使用密码:YES)")

python - 名称错误 : name 'QFileDialog' is not defined

Python:将 cumsum 和 product 应用于 pandas groupby

python - 多维度的 NumPy PolyFit 和 PolyVal?

python - 如何使用 pyplot.jl 中的颜色图作为 julia-lang 中的函数