Reading line by line in python

I have the following line, which is created using tkinter, and then read using textEntry.get():

"
=========New Coffee Order===============
=========Bean Information===============
Type: Ethiopian
Origin: Single

=========Roaster/price==================
Steve Beans
8.50/lb

Everyday Espresso
10.00/lb

Critical Coffee 
6.00/lb


=========End Coffee Order==============
"

I am trying to use fpdf to create a pdf file of this information that follows the formatting guide. My question is this:

How can I tell python to read a string in such a way as to interpret each string, and not just as a list of characters?

My initial idea was to tell python to read this line line by line and assign values ​​to each line. However, it looks like this might be inefficient. Is there a better way to do this?

Thank.

+4
source share
3 answers

str.split('\n') will do the trick:

In [135]: text.split('\n')
Out[135]: 
['"',
 '=========New Coffee Order===============',
 '=========Bean Information===============',
 'Type: Ethiopian',
 'Origin: Single',
 '',
 '=========Roaster/price==================',
 "Steve Beans",
 '8.50/lb',
 '',
 'Everyday Espresso',
 '10.00/lb',
 '',
 'Critical Coffee ',
 '6.00/lb',
 '',
 '',
 '=========End Coffee Order==============',
 '"']

, , :

for line in text.split('\n'):
    ...

@Robα΅© :

In [137]: %timeit text.splitlines()
1000000 loops, best of 3: 1.8 Β΅s per loop

In [138]: %timeit text.split('\n')
1000000 loops, best of 3: 1.31 Β΅s per loop
+6

str.splitlines() .

:

, . .

lines = text.splitlines()
+7

Assuming the lines are separated by UNIX line breaks and the text is in a variable named text

lines = text.split("\n") 

will do the job. Then you can iterate over the list linesand do what you need to do for each line.

+2
source

Source: https://habr.com/ru/post/1680990/


All Articles