如何仅使用查找和替换来查找和计算字符串中子字符串的所有出现次数? [英] How do I find and count all the occurrences of a substring in a string using only find and replace?
本文介绍了如何仅使用查找和替换来查找和计算字符串中子字符串的所有出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
条目需要更低,最后程序必须打印出现次数.例如内存.
The entry needs to be lower and in the end the program must print the number of occurrences. For example mem.
smthing = str(input())
if (smthing == smthing.lower()):
smthing.find(mem)
我对此完全崩溃,所以我走不了多远.
I'm a total wreck at this so I couldnt go far.
我忘了说我不能使用计数或列表.
I forgot to tell that I can't use count or list.
推荐答案
像这样的事情怎么样
string = "hello world hello".lower()
replace = "hello".lower()
count = 0
while string.find(replace) != -1:
string = string.replace(replace, "", 1)
count += 1
print count
# => Output
# => 2
<小时>
为了处理重叠的字符串,而不是替换整个子字符串,我们可以只替换单个字符,最好是第一个,replace[0]
来自原始字符串
string = "boboobobobobob".lower()
replace = "bob".lower()
count = 0
while string.find(replace) != -1:
string = string.replace(replace[0], "", 1)
count += 1
print count
# Output
# => 6
这篇关于如何仅使用查找和替换来查找和计算字符串中子字符串的所有出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文