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.
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
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With