Python 字符串计数无法正常工作?

标签 python string function count

<分区>

“ababa”中出现了两次“aba”(第 0 个索引和第 2 个索引):

myString = 'ababa'
print(myString.count('aba'))

但是这段代码输出的值为:1
我知道这个问题看起来很简单,但这里的答案不应该是 2 吗?
如果不是,那么 count 函数是不是没有真正做它应该做的事情?

有没有简单的替代方案?

最佳答案

来自Python string function documentation

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

count 不计算重叠次数。

如果你想计算重叠的次数,你可以使用带有前瞻断言的正则表达式:

import re
print(len(re.findall('(?=aba)', 'ababa')))

关于Python 字符串计数无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37980821/

相关文章:

python - 如何使用 discord.py 列出 discord 服务器中的所有成员?

python - 找不到 GLIBCXX_3.4.29

c# - 自动编辑字符串以删除空格 C#

c# - 计算字符串数组中元素的数量 C#

c++ - C++中的函数GetCursorPos()和SetCursorPos()的一些问题

sql - 通过 View 或函数重用 sql

python - 让 Python 忽略 .pyc 文件

Python - 在单词后拆分句子但结果最多为 n 个字符

python - 当分隔符两侧的字符不是数字时,在 python 中分割字符串

c - Arduino 不同函数中具有两个值的全局变量