[英]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.