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