Python 字符串计数无法正常工作? [英] Python string count not working properly?

查看:33
本文介绍了Python 字符串计数无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are two occurrences of 'aba' in 'ababa' (0th index and 2nd index):

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

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

Yet this code outputs a value of: 1
I know this issue seems really simple, but shouldn't the answer be 2 here?
If not, then isn't the count function not really doing what it's supposed to?

有没有简单的替代方案?

Is there a simple alternative?

推荐答案

来自 Python 字符串函数文档

返回 [start, end] 范围内子字符串 sub 的非重叠出现次数.可选参数 start 和 end 被解释为切片符号.

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 不计算重叠出现的次数.

count does not count overlapping occurrences.

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

If you want to count overlapping occurrences you can use regex with a lookahead assertion:

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

这篇关于Python 字符串计数无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆