当循环字符串索引超出范围时?

2024-09-21 03:28:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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

在我的控制台中出现这个错误:

^{pr2}$

怎么了?在


Tags: trueif错误contents语法notcurrentelse
2条回答

在你开始之前我假设你有这样的东西:

file = "section_1;section_2;section_3;"
lengthOfFile = len(file)
contents = []
current = ""
fileIndex = 0
endFound = False

您编写的代码可以稍微澄清如下:

^{pr2}$

这个特殊情况下的问题是,当你到达file中的最后一个;fileIndex是17,但是{}是18。所以fileIndex == lengthOfFile测试失败。您可以通过将这一行更改为fileIndex + 1 == lengthOfFile,或者将增量操作移动到if next_char == ';'上方来修复上面的代码。在

但是有更简单的方法用Python编写这些代码。特别是,如果您的目标是使contents成为file中所有“section”条目的列表,则可以使用如下方法:

contents = [part + ';' for part in file[:-1].split(';')]

[:-1]在拆分前省略了file中的最后一个字符(;)。请注意,如果这是您想要的,那么您的原始代码也需要在每次传递期间重置current的值,如上所述。在

如果您真的希望contentsfile的开头开始,将contents变成一个越来越长的子字符串的列表,您可以这样做:

contents1 = file[:-1].split(';')
contents = []
for part in contents1:
    current = current + part + ';'
    contents.append(current)
  1. 在进入循环之前,fileIndex的值是多少?

  2. 检查字符串的结尾(if fileIndex == lengthOfFile:)是否在if file[fileIndex] == ';':内,因此如果字符串中没有;,那么实际上就是无限循环。

  3. 对字符的操作不是很像python,有可能有更有效的工具来执行您的操作(比如.index方法的str等等)

相关问题 更多 >

    热门问题