Python字符串计数不能正常工作? [英] Python string count not working properly?
问题描述
在'ababa'中出现了'aba'两次(第0个索引和第2个索引):
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?
有没有简单的选择?
推荐答案
返回范围[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
可以
如果要计算重复出现的次数,则可以将正则表达式与前瞻性断言一起使用:
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屋!