python - 如何修复此代码以识别重叠字符串?

标签 python string substring overlapping

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/

相关文章:

c++ - 如何使用 SWIG 将 C++ operator[] 包装在命名空间内的模板类中?

python - 将数字分解为其他数字

linux - 在ksh中获取字符串的最后n个字符

php - 如何查找数组项以特定字母开头的所有场合

Python 在 if/else 循环中打印lines.append()

python - 子进程在使用多处理时不考虑参数

c++ - 此代码如何显示此输出?

c# - 我可以使用 Format 而不是使用 substring 吗?

Python - 将字符串拆分为字符,同时排除某个子字符串

python - 主管启动 Gunicorn 时出现问题