【发布时间】:2016-03-17 02:04:16
【问题描述】:
我是一只 30 年前使用 BASIC 的老狗。我之前在 python 中使用 for 循环时遇到过这种情况,但我选择这个插图是因为我担心循环:
我想解析一个长字符串,其中包含用逗号分隔的双引号中的单词。我可以忽略双引号,但我希望循环在这里推进。我不觉得这很优雅。我带着不必要的循环行李。我是否应该完全取消循环,在这种情况下,切片是首选方法,是否有一般规则适用于使用循环的问题?
"""
data is the str-type variable
line, despite the name, seems to pull out just one character at a time
(which is not relevant except to confirm my naïveté in python)
"""
for line in data:
if line.endswith('"'):
x = True # doing nothing but advancing the for loop
elif line.endswith(','):
# do something at a comma
else:
# continue the parsing
编辑示例字符串:
"All","the","world","'s","a","stage","And","all","the","men","and","women","merely","players"
【问题讨论】:
-
你可以使用
continue来推进一个循环 -
循环遍历一个字符串一次拉出一个字符,因为这是定义的行为。我不知道还能怎么说。您可以尝试阅读 official Python tutorial 之类的内容。
-
是的,你绝对应该重命名
line。这对初学者来说非常具有误导性/令人困惑。 -
谢谢@idjaw;添加了示例输入。我不知道继续命令@cricket_007,谢谢。
-
你从哪里得到字符串?可能有更好的方法来解析您的数据。