Python字符串计数不移位计数?
我的问题是python只根据它搜索的字符数来计算出现次数Python字符串计数不移位计数?,python,string,Python,String,我的问题是python只根据它搜索的字符数来计算出现次数 a = "01010101" print(a.count("010")) Pythons字符串计数以2结尾。但据我统计,有3次 #x = "01010101" # --- <-- occurrence 1 # --- <-- occurrence 2 # --- <-- occurrence 3 #x=“0101010
a = "01010101"
print(a.count("010"))
Pythons字符串计数以2结尾。但据我统计,有3次
#x = "01010101"
# --- <-- occurrence 1
# --- <-- occurrence 2
# --- <-- occurrence 3
#x=“01010101”
#--在count()
中,字符串的一部分似乎不能多次用于不同的事件
“01010101”
---您可以使用re
例如:
import re
a = "01010101"
print(len(re.findall(r"(?<=0)1(?=0)", a)))
python str objects的计数方法根据docs对非重叠字符串进行计数。因此,如果“01010”“010”只出现一次,因为在找到第一个匹配项后,它会从该点开始扫描,并且只有“10”不是“010”,这里有一个关于计算重叠字符串的教程:
另请参见此问题:这是否回答了您的问题?
import re
a = "01010101"
print(len(re.findall(r"(?<=0)1(?=0)", a)))
3