【发布时间】:2012-02-15 11:00:30
【问题描述】:
代码:
count = 0
oldcount = 0
for char in inwords:
if char == " ":
anagramlist.append(inwords[oldcount, count])
oldcount = count
count = 0
else:
count += 1
错误:
Traceback (most recent call last):
File "C:/Users/Knowhaw/Desktop/Python Programs/Anagram solver/HTS anagram.py", line 14,
in <module>
anagramlist.append(inwords[oldcount, count])
TypeError: string indices must be integers
这到底是怎么回事? count 和 oldcount 显然是整数,但错误表明它们不是
我什至会写
anagramlist.append(inwords[int(oldcount), int(count)])
得到同样的错误
【问题讨论】:
-
奇怪的标题把我拉到了这里……
-
我可以看到如何将错误消息解释为暗示支持使用多个整数进行索引。 “字符串索引必须是整数”会更清楚。只是一个观察......
-
@chepner:对于初学者来说,它确实看起来令人困惑,但文档 [docs.python.org/tutorial/introduction.html] 足够清晰
Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon. >>> >>> word[4] 'A' >>> word[0:2] 'He' >>> word[2:4] 'lp' -
@chepner: 并且该消息还暗示(如果有人不知道)索引除了访问字符串中的单个符号之外还有其他用途