Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Takewhile lambda function not recognizing string

So I have a comment section at the start of my file. What I want is for the line that starts ‘# Description: ‘ to be pulled. But for some reason I don’t understand, it isn’t working.
Entering ‘#’ gets what I expect, as does ‘# NOTE’, but ‘# Description: ‘ and even ‘# D’ seems to return nothing. Can someone help me understand this?

Here’s my file’s comment section:

# NOTE: successive whitespace characters treated as single delimiter
# NOTE: all lines beginning with '#' treated as comments
# NOTE: Description must come after '# Description: ' to be recognized
#
# Description: High dispersion optics with O-16 (4+) at 6 MeV/nucleon. Provided by <first, last> on <datetime>.
#
#

Here’s the code I’m using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from itertools import takewhile
with open(pathname, 'r') as fobj:
    # takewhile returns an iterator over all the lines
    # that start with the comment string
    headiter = takewhile(lambda s: s.startswith('# Description: '), fobj)
    description = list(headiter)

>Solution :

takewhile will keep the elements from the iterator until the condition is False. In your case, the condition is False in the beginning and only becomes True on the third line.

You want to use dropwhile and next:

from itertools import dropwhile
with open(pathname, 'r') as fobj:
    # dropping lines until they don't start with "# Description:"
    headiter = dropwhile(lambda s: not s.startswith('# Description: '), fobj)
    # getting next element
    description = next(headiter)

output:

'# Description: High dispersion optics with O-16 (4+) at 6 MeV/nucleon. Provided by <first, last> on <datetime>.'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading