Python - 在字符串中查找子字符串(代码不起作用)

标签 python

我正在编写一个代码,您在其中输入一个字符串 (i) 和一个子字符串 (sb),代码应该计算子字符串在字符串中出现的次数(有重叠)。

如果您输入字符串“AAAA”并查找“A”((返回正确的数量,4),则该代码有效,但如果您输入“ADAM”并查找“A”,它将陷入无限循环。

我这辈子都解决不了这个问题。

i = input("Enter a string:")
sb = input("Enter a substring:")

count = 0
x = 0    #index from the string found
idxTotal = len(i)  

while True:

    i.find(sb,x)

    if x != idxTotal:
        count += 1
        x = i.find(sb,x)+1

    else:
        break

print(count)

最佳答案

我认为你把事情搞得太复杂了。基本上,您应该在 while 循环中检查我们是否没有到达字符串的末尾。此外,您应该通过增加偏移值来保证进度。

所以我们可以这样写:

x = i.find(sb)
n = 0
while x >= 0:
    n += 1
    x = i.find(sb, x+1)
# here n is the number of occurrences
print(n)

因此,首先我们执行 i.find(sb) 来查找第一个匹配项,然后每次 n (计数)设置为零x >= 0,我们找到下一个出现的位置,因此我们递增 n,然后查找下一个出现的位置。

我们继续这样做,直到.find(..)返回-1。在这种情况下,while 循环将停止,n 将包含元素数量。

例如:

>>> i = 'ADAM'
>>> sb = 'A'
>>> x = i.find(sb)
>>> n = 0
>>> while x >= 0:
...     n += 1
...     x = i.find(sb, x+1)
...
>>> print(n)
2

这也执行重叠计数,例如:

>>> i = 'AAADAAAAAM'
>>> sb = 'AAA'
>>> x = i.find(sb)
>>> n = 0
>>> while x >= 0:
...     n += 1
...     x = i.find(sb, x+1)
...
>>> print(n)
4 

因此,对于 'AAADAAAAAM',有四个与 'AAA' 的匹配项:

  AAADAAAAAM
1 AAA
2     AAA
3      AAA
4       AAA

关于Python - 在字符串中查找子字符串(代码不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496604/

相关文章:

循环的Python错误

python - 性能:Python pandas DataFrame.to_csv append 逐渐变慢

python - 使用 pyflakes 插件运行 vim 时出错

python - 我需要这个子字符串计数程序来返回一个元组

python - 是否可以使用 weasyprint 对页脚进行精美的格式化?

python - 在 Pandas 中为组切片设置值的最快方法

python - 如何使用现有的 conda 环境作为 AzureML 环境

python - 使用 cscope 用 VIM 浏览 Python 代码?

python - 如何使用 os.execv() 在 python 中继承 stdin 和 stdout

python - 如何在没有 sudo 的情况下发送自定义 'TCP' 数据包 - 没有三向握手