python advance for loop

时间:2016-03-17 02:04:17

标签: python loops for-loop

我是一只使用BASIC>的老狗。 30年前。我之前在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"

4 个答案:

答案 0 :(得分:4)

  

我想解析一个长字符串,其中包含用逗号分隔的双引号中的单词

data成为

data = '''"this","is","a","test"'''

然后你可以用逗号<{1}}

split()
  

我可以忽略双引号

是的,你可以for quote in data.split(','): 报价

strip()

然后打印

    word = quote.strip('"')

一起

    print(word)

输出

data = '''"this","is","a","test"'''

for quote in data.split(','):
    word = quote.strip('"')
    print(word)

答案 1 :(得分:3)

关于循环的一般问题,如果你想逐行解析字符串,你可以这样做:

for line in data.split('\n'):
    …

for line in data.splitlines():
    …
  

... 长字符串,包含用逗号分隔的双引号中的单词。我可以忽略双引号,但我希望循环在这里前进 ...

但是在多次阅读你的问题之后,你从未说过你真的想要在线上进行迭代。相反,您可能希望以逗号分隔字符串:

for element in data.split(','):
    …

然后,如果你想删除引号,你可以将它们删除:

    element.strip('"\'')

编辑:

这里有你的例子,提取每个单词:

>>> s = '''"All","the","world","'s","a","stage","And","all","the","men","and","women","merely","players"'''
>>> 
>>> for element in s.split(','):
...     element = element.strip('"')
...     print(element)
... 
All
the
world
's
a
stage
And
all
the
men
and
women
merely
players

HTH

答案 2 :(得分:1)

由于datastr,for循环将一次前进一个字符。如果要将str拆分为换行符分隔的行,可以通过返回行列表的split方法执行此操作:

for line in data.split('\n'):
    # do something with line

答案 3 :(得分:0)

假设您的data是一个包含

之类的字符串
"one", "two", "tree", ...

你可能会将你的行分成&#34;一个&#34;,&#34;两个&#34;和&#34;树&#34; chunk并摆脱这样的引号:

for element in [x[1:-1] for x in data.split(",")]:
    print element

这使用了所谓的list comprehensions