【问题标题】:How do I fix this code to recognise overlapping strings?如何修复此代码以识别重叠字符串?
【发布时间】:2015-04-24 17:44:20
【问题描述】:
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

【问题讨论】:

  • 首先我不知道你为什么要在降低后转换为字符串。如果输入不是字符串,lower 很可能会抛出AttributeError。还有我的问题 - 用户同时提供子字符串和字符串?
  • 只有字符串并且必须更低
  • 您是否尝试过来自其他线程的my approach?哎呀,对不起,不是你。

标签: python string substring overlapping


【解决方案1】:

这样做的一种方法是使用str.find 的第二个参数,它指示一个可选的索引来开始搜索字符串中的子字符串。

来自docs

str.find(sub[, start[, end]])¶ 返回字符串中的最低索引 找到子字符串 sub 的位置,使得 sub 包含在切片中 s [开始:结束]。可选参数 start 和 end 被解释为 切片符号。如果未找到 sub,则返回 -1。

因此,如果我们跟踪在变量中找到的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)

【讨论】:

    【解决方案2】:

    你可以使用

    i = 0
    while True:
        i = entrada.find(replace, i) + 1
        if i:
             count += 1
        else:
            break
    

    这将在entrada 中找到replace,增加计数,在entrada[i+1:] 中找到replace,其中i 是上一场比赛的开始,增加计数,然后永远重复。

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 2020-07-05
      • 2014-07-12
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多