jcloudz1 jcloudz1 - 3 years ago 211
Python Question

Trying to iterate through a string to find a substring but keep getting a TypeError: must be str, not int on -> if s[i: i+3] == 'bob':

I am getting the error

TypeError: must be str, not int on -> if s[i: i+3] == 'bob':

when executing the following code:

number_of_times = 0


for i in s:

if s[i: i+3] == 'bob':

number_of_times += 1


Could anybody please explain why?

Answer Source

What you need to do is change your for loop as :

for i in range(len(s)):                   #point of interest
   if s[i: i+3] == 'bob':
      number_of_times += 1

Here, when you do for i in s , your value of i is char.

For ex :

for i in s:

So when you do s[i], you are basically doing something like s['b'] , which is wrong.

Anyways, its better to use find, an inbuilt function to find the starting index of your substring. If not found, it returns -1.

Ex :

>>> s="hi i am bob !"
>>> s.find('bob')
=>  8

Or, if you want to count the number of times a substring occurs, use count, another inbuilt funciton.

Ex :

>>> s="hi bob ! bob is a man" 
>>> s.count('bob')
=> 2
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download