![](/img/trans.png)
[英]How to get rid of this index out of range error? I know the reason but don't know the solution
[英]In My Code There Is A Error Saying "Index Out Of Range" For Some Reason, I Actually Just Started Python And Hence Don't Know How To Solve This
for w in 'words':
if w[4] == 'z':
print(w)
在此代码第 3 行,它说:-
Traceback (most recent call last):
File "main.py", line 4, in <module>
if w[4] == 'z':
IndexError: string index out of range
我找不到解决方案,请尝试帮助
它应该是这样的,因为在你的代码中“for w in "words":” w 代表字符 'w','o','r','d','s' 所以如果你正在访问 'w' [4] 它会产生一个错误,因为你的角色中没有 4 值
for w in 'words':
if w == 'z':
print(w)
或者你可以看看这个
for w in range(len("words")):
if words[w]=="z"
print(words[w])
索引是 Python 和许多不同编程语言中非常有价值的工具。 它允许您在结构中选择一个元素。 在这里阅读。 你的问题是你不能用单个字符索引字符串的第 4 个字符。
在您的代码示例中,您循环遍历字符串 'words' 并且在每次迭代中,变量 w 都填充了每个字母。 因此,在第一次迭代时,w 是 'w',然后是 'o',然后是 'r',依此类推。 因此,当您索引 w 变量时,您要求的是一个不存在的字母。
尝试:
for w in 'words':
if w == 'z':
print(w)
您的代码不正确。 您正在尝试使用w迭代字符串words ,因此w是一个字符,但您将其视为列表。 您可以尝试删除for循环
if w[4] == 'z':
print(w)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.