warspyking
warspyking

Reputation: 3113

Python thinks my tuple is an integer

I am trying to print out the positions of a given substring inside of a string, but on line 18 I keep getting the error

Traceback (most recent call last): File "prog.py", line 18, in <module> TypeError: 'int' object has no attribute '__getitem__'

I have no idea why this is happening, because I am new to python. But anyway, here's my program:

sentence = "one two three one four one"
word = "one"

tracked = ()
n = 0
p = 0
for c in sentence:
    p += 1
    if n == 0 and c == word[n]:
        n += 1
        tracked = (p)
    elif n == len(word) and c == word[n]:
        print(tracked[1], tracked[2])
        tracked = ()
        n = 0
    elif c == word[n]:
        n += 1
        tracked = (tracked[1], p)
    else:
        tracked = ()
        n = 0

Upvotes: 2

Views: 1619

Answers (1)

SuperBiasedMan
SuperBiasedMan

Reputation: 9969

tracked = (p) is an integer, not a tuple. The brackets don't necessarily create a tuple, because they're also used for operator precedence in expressions. In this case, it's just evaluating it as an expression so (p) gets evaluated to p. If you wanted to make it a tuple, you'd need to add a comma (p,) which makes it a tuple.

Though in your case you're trying to call tracked[1], tracked[2], neither of which will be valid for a single item tuple. It's unclear what you're trying to do, but tuples are explicitly immutable (meaning they don't change, can't be appended to etc.) and it seems like lists are more likely what you'd need.

Upvotes: 8

Related Questions