Python Slicing 'bob' in s [duplicate]

2019-06-03 18:49发布

This question already has an answer here:

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

Attempting to write a code that will count the amount of times 'bob' appears in s, but for some reason this always outputs 0 for number of 'bob'.

标签: python slice
3条回答
倾城 Initia
2楼-- · 2019-06-03 19:29

x is a number, it can't be equal to 'bob'. That's why it always output 0.

You should use x in order to get a substring of s:

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

You can also use enumerate.

查看更多
我命由我不由天
3楼-- · 2019-06-03 19:54
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))

Working example.

But the best way is this, however it does not work with overlapping strings:

s.ount('bob')
查看更多
太酷不给撩
4楼-- · 2019-06-03 19:55

Here, try this, handcrafted :)

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

Demo

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

Hope this helps!

查看更多
登录 后发表回答