python 高级 for 循环

Jep*_*tha 5 python loops for-loop

我是一只老狗,30 多年前就使用过 BASIC。我之前在 python 中使用 for 循环时遇到过这种情况,但出于对循环的担忧,我选择了这个插图:

\n\n

我想解析一个长字符串,其中包含用逗号分隔的双引号中的单词。我可以忽略双引号,但我希望循环在这里前进。我不觉得这很优雅。我携带不必要的循环行李。我是否应该完全取消循环,在这种情况下,切片是首选方法,并且是否有适用于使用循环的问题的一般规则?

\n\n
"""\ndata is the str-type variable\nline, despite the name, seems to pull out just one character at a time\n(which is not relevant except to confirm my na\xc3\xafvet\xc3\xa9 in python)\n"""\n\nfor line in data:\n    if line.endswith(\'"\'):\n        x = True  # doing nothing but advancing the for loop\n    elif line.endswith(\',\'):\n        #  do something at a comma\n    else:\n        #  continue the parsing\n
Run Code Online (Sandbox Code Playgroud)\n\n

编辑示例字符串:

\n\n
"All","the","world","\'s","a","stage","And","all","the","men","and","women","merely","players"\n
Run Code Online (Sandbox Code Playgroud)\n

cri*_*007 5

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

data这样吧

data = '''"this","is","a","test"'''
Run Code Online (Sandbox Code Playgroud)

然后你可以split()用逗号

for quote in data.split(','):
Run Code Online (Sandbox Code Playgroud)

我可以忽略双引号

是的,您strip()可以引用

    word = quote.strip('"')
Run Code Online (Sandbox Code Playgroud)

然后打印

    print(word)
Run Code Online (Sandbox Code Playgroud)

全部一起

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

for quote in data.split(','):
    word = quote.strip('"')
    print(word)
Run Code Online (Sandbox Code Playgroud)

输出

this
is
a
test
Run Code Online (Sandbox Code Playgroud)