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))
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
正在工作example。
但是,最好的方法是这样,但是它不适用于重叠字符串:
x
是一个数字,它不能等于'bob'
。这就是为什么它总是输出0。您应该使用
x
来获得s
的子字符串:您也可以使用
enumerate
。来,试试这个,手工制作的:)
演示
希望这有帮助!
相关问题 更多 >
编程相关推荐