python - 查找子字符串在字符串中存在的次数 - Python

标签 python string

<分区>

我正在尝试查找子字符串的次数,在本例中,“bob”出现在字符串中。我的解决方案适用于某些字符串,但不适用于所有字符串。例如,下面的答案应该是 7,但我返回 5。

有什么想法吗?

谢谢

s = 'bobbisbobobugbobobbobbobo'
print('Number of times bob occurs is: ', s.count('bob'))

最佳答案

问题是 s.count() 返回 [start, end] 范围内子字符串 sub 的非重叠出现次数。

要计算重叠的字符串使用正则表达式

import re

text = 'bobbisbobobugbobobbobbobo'
print(len(re.findall('(?=bob)', text)))

关于python - 查找子字符串在字符串中存在的次数 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46046287/

相关文章:

python - 调用序列化器的 post 方法并向其传递数据

c# - 为什么 String.Contains 不直接调用最终重载?

python - Django 连接多个带注释的查询集

Python 从 excel 数据创建字典

string - 如何检查一个List容器是否包含另一个List中的所有元素

string - 如何将 Rust 字符串转换为 UTF-16?

c++ - while 循环中的减法。 C++

使用c复制文本文件

python - 使用本地私钥通过 web3.py 发送 ERC20 token

python - 如何使用 Pandas DataFrame 读取包含图像像素值的 csv 文件