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

how would I check for a word a string that has multiple words in a list?

I need help looking for a way to check for words within a string that is part of a list, EX:

list = ["brown cow", "brown cat", "blue mouse"]

How would I search just for the word brown in the strings and be able to get the whole variable name from that to be used in something else?

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

>Solution :

If you want to filter your list by keywords, then you could use in with a list comprehension:

list = ["brown cow", "brown cat", "blue mouse"]
output = [x for x in list if "brown" in x]
print(output)  # ['brown cow', 'brown cat']

But a safer approach would be to use re.search:

list = ["brown cow", "brown cat", "blue mouse"]
output = [x for x in list if re.search(r'\bbrown\b', x)]
print(output)  # ['brown cow', 'brown cat']
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