我需要在像ACACA这样的字符串中找到像'ACA'这样的子字符串的数量。我试过count(str)
方法,但它只给了我 1 而不是 2。我怎样才能找到这些字符串在 python 中的实际出现次数?
最佳答案
count
的文档 method of strings说:
Return the number of non-overlapping occurrences of substring sub in the range [start, end].
您的子字符串重叠,这就是为什么 count
方法没有执行您想要的操作。您可以使用 find
方法的可选参数从字符串开头以外的位置开始查找计数:
string = 'ACACA'
substr = 'ACA'
substr_count = 0
start = 0
while True:
loc = string.find(substr, start)
if loc == -1:
break
substr_count += 1
start = loc + 1
该例程的循环计数与字符串中子字符串的出现次数相同。您可以使用一个更简单的例程来检查字符串的每个位置,以查看子字符串是否位于该位置,但这需要更多循环并且速度会更慢。
关于python - Python 中的连续子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690245/