Python切片'bob'在s

时间:2013-10-27 10:37:31

标签: python slice

    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中的次数,但由于某种原因,它总是输出0表示'bob'。

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

在这里,试试这个,手工制作:)

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

希望这有帮助!

答案 2 :(得分:1)

x是一个数字,不能等于'bob'。这就是它总是输出0的原因。

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

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

您也可以使用enumerate