我正在编写一个程序,用于计算并删除子字符串的出现次数。这两个操作都是逐个执行的。
然而,并非所有情况下都适用:
正确工作:
string = abbab
substring = ab
Occurrences = 2
不起作用:
string = abab
substring = ab
Occurrences: 1 # should be 2
以下是代码:
def count_delete(string, substring):
occurrence = 0
for i in range(len(string)):
if string[i:i + len(substring)] == substring:
occurrence += 1
string = string.replace(substring, "", 1)
return occurrence
def main():
string = 'abbab'
substring = 'ab'
count = count_delete(string, substring)
print("Occurrences:", count)
if __name__ == '__main__':
main()
我如何在所有情况下都获得正确的输出?
string
,为什么要修改它呢?将替换行移动到 for 循环之后,并通过删除 1 参数来替换所有出现的值。 - RichieV