Home > other >  Takewhile lambda function not recognizing string
Takewhile lambda function not recognizing string

Time:12-07

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:

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)

CodePudding user response:

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>.'
  • Related