Python在字符串中查找子字符串(代码不工作)

2024-06-09 15:05:20 发布

您现在位置: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)

Tags: 字符串代码inputstringindexcountsubstringfind
3条回答

由于find方法在没有找到子字符串时返回-1,所以我将使用它来结束while循环。在

通过执行以下操作进行计数,直到找不到子字符串:

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

count = 0
x = 0  

while True:
    x = i.find(sb,x)+1  #x will be 0 if sb isn't found
    if x != 0:          #if x = 0 the while loop will end
        count += 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将包含元素的数量。在

例如:

^{pr2}$

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

>>> 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

你能试试吗

some_string = input("Enter a string:")
some_substring = input("Enter a substring:")
total = 0
for index, some_char in enumerate(some_string):
  # print(index, some_char) # try this to see what comes in the loop
  if some_string[index:].startswith(some_substring):
    total = total + 1

print(total)

它更优雅,避免使用while(True)也i.find将返回-1,因此您将陷入无限循环。这将允许您避免使用while手动索引。:)

这将适用于“ADAM”和“A”的正确2,也适用于其他子字符串,如“DABCEABC”和“ABC”,正确的2,“aaadaaaam”和“AAA”的正确5。在

相关问题 更多 >