Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在python中;巴巴布;。计数(“BAB”等于1?_Python - Fatal编程技术网

为什么在python中;巴巴布;。计数(“BAB”等于1?

为什么在python中;巴巴布;。计数(“BAB”等于1?,python,Python,IMO子串BAB在BABAB中出现2次 为什么Python返回1 print "BABAB".count("BAB") 如有任何帮助,将不胜感激 返回子字符串的非重叠出现次数 范围[开始,结束]中的子对象。可选参数start和end解释为切片表示法 Per(我的重点): 返回子字符串的非重叠出现次数 范围[开始,结束]中的子对象。可选参数start和end解释为切片表示法 字符串是“BABAB”。通过使用count()函数,它将返回如下非重叠匹配的数量:“BAB | AB”,因此它只计算一次

IMO子串BAB在BABAB中出现2次 为什么Python返回1

 print "BABAB".count("BAB")
如有任何帮助,将不胜感激

返回子字符串的非重叠出现次数 范围[开始,结束]中的子对象。可选参数start和end解释为切片表示法

Per(我的重点):

返回子字符串的非重叠出现次数 范围[开始,结束]中的子对象。可选参数start和end解释为切片表示法

字符串是“BABAB”。通过使用count()函数,它将返回如下非重叠匹配的数量:“BAB | AB”,因此它只计算一次。。尝试使用字符串“BABBAB”,您将得到2。例如:

>>> x = "BABAB"
>>> x.count("BAB")
1
>>> x = "BABBAB"
>>> x.count("BAB")
2
字符串是“BABAB”。通过使用count()函数,它将返回如下非重叠匹配的数量:“BAB | AB”,因此它只计算一次。。尝试使用字符串“BABBAB”,您将得到2。例如:

>>> x = "BABAB"
>>> x.count("BAB")
1
>>> x = "BABBAB"
>>> x.count("BAB")
2

‍‍str.count
仅返回,如果要获取所有匹配的数量,包括重叠匹配,可以使用正则表达式与
re.findall

>>> re.findall(r'(?=(BAB))',"BABAB")
['BAB', 'BAB']
对于计算匹配数,您可以在
sum
函数中使用生成器表达式,并使用
re.finditer
而不是
re.findall
,后者在内存使用方面更为优化:

>>> sum(1 for _ in re.finditer(r'(?=(BAB))',"BABAB"))
2

(?=(BAB))
是一个与后面跟着
BAB
的位置相匹配的

‍‍str.count
仅返回,如果要获取所有匹配的数量,包括重叠匹配,可以使用正则表达式与
re.findall

>>> re.findall(r'(?=(BAB))',"BABAB")
['BAB', 'BAB']
对于计算匹配数,您可以在
sum
函数中使用生成器表达式,并使用
re.finditer
而不是
re.findall
,后者在内存使用方面更为优化:

>>> sum(1 for _ in re.finditer(r'(?=(BAB))',"BABAB"))
2

(?=(BAB))
是一个与后面跟着
BAB
的位置相匹配的

count
只查找不重叠的匹配项。查找我要查找的内容:@Gnuz可能在下次询问之前进行研究
count
只查找不重叠的匹配项。查找我要查找的内容:@Gnuz可能在下次询问之前进行研究