如何在python中逐行读取长的多行字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15422144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:04:54  来源:igfitidea点击:

how to read a long multiline string line by line in python

python

提问by DKean

I have a wallop of a string with many lines. How do I read the lines one by one with a forclause? Here is what I am trying to do and I get an error on the textData var referenced in the for line in textDataline.

我有一个多行的字符串冲击。如何用for子句逐行阅读?这是我正在尝试执行的操作,并且在该for line in textData行中引用的 textData var 上出现错误。

for line in textData
    print line
    lineResult = libLAPFF.parseLine(line)

The textData variable does exist, I print it before going down, but I think that the pre-compiler is kicking up the error.

textData 变量确实存在,我在关闭之前打印它,但我认为预编译器正在引发错误。

TIA

TIA

Dennis

丹尼斯

采纳答案by Benjamin Gruenbaum

What about using .splitlines()?

怎么用.splitlines()

for line in textData.splitlines():
    print(line)
    lineResult = libLAPFF.parseLine(line)

回答by thkang

by splitting with newlines.

通过用换行符分割。

for line in wallop_of_a_string_with_many_lines.split('\n'):
  #do_something..

if you iterate over a string, you are iterating char by char in that string, not by line.

如果您迭代一个字符串,那么您是在该字符串中逐个字符地迭代,而不是逐行。

>>>string = 'abc'
>>>for line in string:
    print line

a
b
c

回答by P.R.

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines()is the way to go. I will leave this answer nevertheless as reference.

这个答案在几个边缘情况下失败(见评论)。上面接受的解决方案将处理这些。str.splitlines()是要走的路。尽管如此,我还是会留下这个答案作为参考。

Old (incorrect) answer:

旧(不正确)答案:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)