I am trying to print out the positions of a given substring inside of a string, but on line 18 I keep getting the errorTraceback (most recent call last): File "prog.py", line 18, in <module>TypeError: 'int' object has no attribute '__getitem__'
我不知道为什么会这样,因为我是python新手。但无论如何,我的计划是:
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
最佳答案
tracked = (p)
是整数,而不是元组。括号不一定创建元组,因为它们也用于表达式中的运算符优先级。。。
尽管在您的示例中,您试图调用(p)
,但这两个调用对于单个项元组都无效。目前还不清楚您要做什么,但是元组是显式不可变的(意味着它们不会改变,不能附加到其他元素中),而且似乎列表更可能是您需要的。
关于python - Python认为我的元组是整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33735091/