我在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}$怎么了?在
在你开始之前我假设你有这样的东西:
您编写的代码可以稍微澄清如下:
^{pr2}$这个特殊情况下的问题是,当你到达}是18。所以
file
中的最后一个;
,fileIndex
是17,但是{fileIndex == lengthOfFile
测试失败。您可以通过将这一行更改为fileIndex + 1 == lengthOfFile
,或者将增量操作移动到if next_char == ';'
上方来修复上面的代码。在但是有更简单的方法用Python编写这些代码。特别是,如果您的目标是使
contents
成为file
中所有“section”条目的列表,则可以使用如下方法:(
[:-1]
在拆分前省略了file
中的最后一个字符(;
)。请注意,如果这是您想要的,那么您的原始代码也需要在每次传递期间重置current
的值,如上所述。在如果您真的希望
contents
从file
的开头开始,将contents
变成一个越来越长的子字符串的列表,您可以这样做:在进入循环之前,
fileIndex
的值是多少?检查字符串的结尾(
if fileIndex == lengthOfFile:
)是否在if file[fileIndex] == ';':
内,因此如果字符串中没有;
,那么实际上就是无限循环。对字符的操作不是很像python,有可能有更有效的工具来执行您的操作(比如
.index
方法的str
等等)相关问题 更多 >
编程相关推荐