entrada = str(input().lower())
replace = "mem".lower()
find = entrada.lower()
count = 0
while (entrada.find(replace) != -1):
entrada = entrada.replace(replace, "", 1)
count +=1
print(count)
不能使用计数、列表或 lambda。 我应该制作一个程序,从用户那里接收较低的字符串,然后查找、计数并打印子字符串出现的次数。 但我遇到了重叠字符串的问题。
示例:字符串为 memem,预期退出为 2
最佳答案
实现此目的的一种方法是使用 str.find 的第二个参数它指示开始在字符串中搜索子字符串的可选索引。
来自docs :
str.find(sub[, start[, end]])¶ Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
因此,如果我们跟踪在变量中找到的 last_index
,我们可以简单地在下一个可能的索引中再次开始搜索子字符串。用代码来表达就是这样的表达式
last_index + 1
。如果 last_index
为 -1,我们将停止搜索子字符串并输出计数:
mystr = 'memem'
mysubstr = 'mem'
count = 0
last_index = -1
while True:
last_index = mystr.find(mysubstr, last_index + 1)
if last_index == -1:
break
count += 1
print(count)
关于python - 如何修复此代码以识别重叠字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29854136/