Python在s中切“bob”

2024-09-30 10:27:21 发布

您现在位置:Python中文网/ 问答频道 /正文

    s = 'gfdhbobobyui'
    bob = 0
    for x in range(len(s)):
         if x == 'bob':
             bob += 1
    print('Number of times bob occurs is: ' + str(bob))

试图编写一个计算“bob”在s中出现的次数的代码,但由于某些原因,它总是为“bob”的数目输出0。


Tags: ofinnumberforlenifisrange
3条回答
s = 'gfdhbobobyui'
bob = 0
for x in range(len(s)):
     if s[x:x+3] == 'bob':  # From x to three 3 characters ahead.
         bob += 1
print('Number of times bob occurs is: ' + str(bob))

正在工作example

但是,最好的方法是这样,但是它不适用于重叠字符串:

s.ount('bob')

x是一个数字,它不能等于'bob'。这就是为什么它总是输出0。

您应该使用x来获得s的子字符串:

bob = 0
for x in range(len(s) - 2):
    if s[x:x+3] == 'bob':
        bob += 1

您也可以使用enumerate

来,试试这个,手工制作的:)

for i, _ in enumerate(s): #i here is the index, equal to "i in range(len(s))"
    if s[i:i+3] == 'bob': #Check the current char + the next three chars.
        bob += 1
print('Number of times bob occurs is: ' + str(bob))

演示

>>> s = 'gfdhbobobyui'
>>> bob = 0
>>> for i, v in enumerate(s): #i here is the index, equal to "i range(len(s))"
    if s[i:i+3] == 'bob': #Check the current char + the next two chars.
        bob += 1


>>> bob
2

希望这有帮助!

相关问题 更多 >

    热门问题