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

Python

Python Problem Overview


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

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.

Python Solutions


Solution 1 - Python

What about using .splitlines()?

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

Solution 2 - Python

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

Solution 3 - Python

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.

Old (incorrect) answer:

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDKeanView Question on Stackoverflow
Solution 1 - PythonBenjamin GruenbaumView Answer on Stackoverflow
Solution 2 - PythonthkangView Answer on Stackoverflow
Solution 3 - PythonP.R.View Answer on Stackoverflow