I have a list of words in a list self.terms
, and a string line
. If any of the terms in the list are in line
, I'd like to write them out to a file terms_file
.
I used any()
as shown below, but this returns a boolean.
any(terms_file.write(term) for term in self.terms if term in line)
How can I write out to the file? I tried adding a lambda but I'm not really familiar with them and that did not work. I got some syntax errors, but after some changes, I got False
returned again.
Is it possible to do this using any()
?
Don't use any()
here; you don't even use the return value.
To write all matching terms, use:
terms_file.write(''.join(term for term in self.terms if term in line))
but it'd be better to just use a regular loop; readability counts!
for term in self.terms:
if term in line:
terms_file.write(term)
Use any()
only if you want to know about the boolean result of the test; any()
stops iterating when it finds the first True
value. In your case terms_file.write()
returns None
, so it'll never even encounter True
and always return False
.