Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a string line by line in python [closed]

Tags:

python

string

I have the following string that is generated using tkinter and then read using textEntry.get():

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

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

Everyday Espresso
10.00/lb

Critical Coffee 
6.00/lb


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

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

How can I tell python to read a string in a way that interprets each line and not simply as a list of characters?

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

Thank you.

like image 286
Calvin Ellington Avatar asked Jul 07 '17 20:07

Calvin Ellington


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's Beans",
 '8.50/lb',
 '',
 'Everyday Espresso',
 '10.00/lb',
 '',
 'Critical Coffee ',
 '6.00/lb',
 '',
 '',
 '=========End Coffee Order==============',
 '"']

All you'll need to do is iterate over the returned list, line by line:

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

Comparing @Robᵩ's and my solutions:

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
like image 95
cs95 Avatar answered Oct 13 '22 11:10

cs95


str.splitlines() converts a single multi-line string into a list of single-line strings.

Quoting the documentation:

Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines.

lines = text.splitlines()
like image 25
Robᵩ Avatar answered Oct 13 '22 12:10

Robᵩ


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

lines = text.split("\n") 

will do the job. You can then iterate over the list lines and do what you need to do to each line.

like image 4
Jon Kiparsky Avatar answered Oct 13 '22 11:10

Jon Kiparsky