python - 计数函数 Python

标签 python

我想制作一个功能与计数相同的功能, 不使用计数。 像这样:

>>> count('mama ma emu a ema ma mamu', 'ma ')
4
>>> count('mama ma emu a ema ma mamu', 'am')
2

我怎样才能做到这一点?

最佳答案

我想我会添加一种迭代方法,您可以在其中循环遍历字符串,因为这样更容易理解。

试试这个:

def count(string, substring):

    count = 0

    for i in range(len(string) - len(substring) + 1):
        if string[i: i + len(substring)] == substring:
            count += 1

    return count

本质上,我正在遍历 i 的可能值,其中 i 是每个子字符串的起始索引,其长度与输入的子字符串相同。然后,我只是检查正确长度的每个可能子串是否等同于输入的子串。如果是这样,我将我的 count 加 1。

关于python - 计数函数 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51464483/

相关文章:

python - 如何摆脱 NaturalNameWarning?

python - 将 Django 管理员登录集成为 REST 框架登录

python - 如何使用 PyQt4 禁用窗口最大化图标?

python - 使用变量时如何修改类

python - 正则表达式从 CSV 中删除双引号

python - bool 值的大列表和小列表以及字节数组的相对性能

python :使用 numpy.histogram

python - 一行异常处理

python - 如何将现有的 Django 应用程序转换为在 virtualenv 中运行?

python:导入失败时的库行为