Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 643
DKean Avatar asked Mar 14 '13 23:03

DKean


People also ask

How do you read a multi-line string in Python?

str. splitlines() is the way to go.

How do you print a string line by line in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

How do you read a new line of a string in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

How do I convert multiple lines to one line in Python?

For each line in lines , we call str. strip() to remove any whitespace and non-printing characters from the ENDS of each line. Finally, we call '\t'. join() on the resulting list to insert tabs.


2 Answers

What about using .splitlines()?

for line in textData.splitlines():     print(line)     lineResult = libLAPFF.parseLine(line) 
like image 143
Benjamin Gruenbaum Avatar answered Sep 20 '22 18:09

Benjamin Gruenbaum


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 
like image 20
thkang Avatar answered Sep 21 '22 18:09

thkang