簡體   English   中英

我不明白為什么會收到錯誤“IndexError: string index out of range”

[英]I don't understand why I get the error “IndexError: string index out of range”

輸入:

AEList =[]
    cc = infile.readline().strip()
    while cc != 'EXIT':
        if cc[0] == '3':
            name = 'A'
            AEList.append(cc)
        cc = infile.readline().strip()

OUTPUT:

Traceback (most recent call last):
  File "/Users/alexleblanc/Documents/pa8.py", line 81, in <module>
    main()
  File "/Users/alexleblanc/Documents/pa8.py", line 47, in main
    if cc[3] == '3' :
IndexError: string index out of range

嘗試:

for i=0 in range(len(cc)):
 if cc[i] == '3'

你擺脫你的字符串。

一種解決方案是在檢查特定值之前檢查您的字符串/數組是否為空:

if cc and cc[0] == '3'

或者

if len(cc) > 0 and cc[0] == '3'

請記住,如果您嘗試訪問不存在的索引處的值,您將遇到此錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM