Sam
Sam

Reputation: 37

slicing a string with variables, Typerror: string indices must be integers

I'm trying to write a script that finds the substring 'bob' in a given string. I thought string slicing would be a good way of doing it, but I'm getting "TypeError: string indices must be integers". I'm confused by this as both of the variables I've used as indices are integers as far as I can tell.

Also even if this code is not an efficient way of doing this I am curious as to why I'm having issues using variables as indices as all of my googling has turned up that that is an okay thing to do.

s = 'azcbobobegghakliia'

bob = 'bob'
startindex = 0
endindex = 2
numBob = 0

while len(s) > endindex:
    if s[startindex,endindex] == 'bob':
        numBob += 1
        startindex += 1
        endindex += 1
print(numBob)

I expected it to print 2 as 'bob' is contained twice in this string (...bobob...). The actual output is "TypeError: string indices must be integers"

Upvotes: 1

Views: 39

Answers (1)

Draconis
Draconis

Reputation: 3461

Comma-separated variables by default make a tuple. You want to use : to make a slice instead.

Longer explanation: a[b,c] is equivalent to a[(b,c)], that is, a indexed with the tuple (b,c). To get the elements from b to c, you need a[b:c].

Upvotes: 1

Related Questions