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\nRun Code Online (Sandbox Code Playgroud)\n\n编辑示例字符串:
\n\n"All","the","world","\'s","a","stage","And","all","the","men","and","women","merely","players"\nRun Code Online (Sandbox Code Playgroud)\n
我想解析一个长字符串,其中包含用逗号分隔的双引号中的单词
就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)