Python Slicing 'bob' in s [duplicate]

亡梦爱人 提交于 2019-12-08 08:12:49

问题


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


回答1:


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!




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

Working example.

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

s.ount('bob')



回答3:


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.



来源:https://stackoverflow.com/questions/19617125/python-slicing-bob-in-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!