[英]While Loop - String Index out of Range?
我用這種語法在Python中運行while
循環:
while not endFound:
if file[fileIndex] == ';':
current = current + ';'
contents.append(current)
if fileIndex == lengthOfFile:
endFound = True
else:
current = current + file[fileIndex]
fileIndex = fileIndex + 1
我在我的控制台中收到此錯誤:
var(vari) = 0;terminal.write(vari);var(contents) = file.getContents('source.py');if(vari : 0) { terminal.write('vari equals 0');}
Traceback (most recent call last):
File "/home/ubuntu/workspace/source.py", line 30, in <module>
splitFile(content)
File "/home/ubuntu/workspace/source.py", line 22, in splitFile
if file[fileIndex] == ';':
IndexError: string index out of range
> Process exited with code: 1
發生了什么?
在你開始之前,我假設你有類似的東西:
file = "section_1;section_2;section_3;"
lengthOfFile = len(file)
contents = []
current = ""
fileIndex = 0
endFound = False
您編寫的代碼可以稍微澄清如下:
while not endFound:
next_char = file[fileIndex]
current = current + next_char
if next_char == ';':
contents.append(current)
#? current = ''
if fileIndex == lengthOfFile:
endFound = True
fileIndex = fileIndex + 1
這個特殊情況下的問題是當你到達決賽時;
在file
, fileIndex
為17,但lengthOfFile
為18.因此fileIndex == lengthOfFile
測試失敗。 您可以通過將此行更改為fileIndex + 1 == lengthOfFile
,或者通過移動上面的增量操作來修復上面的代碼, if next_char == ';'
。
但是有更簡單的方法可以在Python中編寫此代碼。 特別是,如果你的目標是讓contents
成為所有“section_n”的列表 file
條目,你可以使用這樣的東西:
contents = [part + ';' for part in file[:-1].split(';')]
(在[:-1]
省略了最后一個字符( ;
從) file
拆分前)。需要注意的是,如果這是你想要的東西,那么你原來的代碼也需要重置的價值current
每個過程中,如上所述。
如果你真的希望contents
從file
的開頭變成一個更長和更長的子串的列表,那么你可以這樣做:
contents1 = file[:-1].split(';')
contents = []
for part in contents1:
current = current + part + ';'
contents.append(current)
進入循環之前fileIndex
的值是fileIndex
?
檢查字符串的結尾( if fileIndex == lengthOfFile:
在if file[fileIndex] == ';':
,如果沒有;
在字符串中,你實際上有無限循環。
使用字符的操作不是非常pythonic,有很多可能更有效的工具來做你的事情(比如str
.index
方法等等。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.