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

Pyhton: Remove strings from list that doesn't contain specific string but not exact match

I have a list of strings

e.g:

kw_list = 
       ['facebook',
        'google',
        'bank',
        'bank cd rates', 
        'forever 21', 
        'bank rates',
        'bank of america mortgage rates',
        'bank exchange rates']

and I have a string

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

e.g:

keyword = 'bank rates'

I want to be able to remove anything from the list that doesn’t contain my string in this case bank rates. But I don’t want to remove it as an exact match.

So after cleaning the list it would look something like this:

kw_list = [
        'bank cd rates', 
        'bank rates',
        'bank of america mortgage rates',
        'bank exchange rates']

I tried using:

new_kws = []
     for i in kw_list:
                if keyword in i:
                    new_kws.append(i)
                    print('It has the word',keyword , '--->' ,i)
                else:
                    print('it doesnt have the word ---> ', i)

But this only looks for the exact match of ‘bank rates’ and in the following example this code will remove strings like bank cd rates, bank of america mortgage rates and bank exchange rates' So it will leave the list as:

   kw_list = [
            'bank rates',
           ]

What would be the best way of achieving what I want?

>Solution :

You can use:

new_list = [word for word in kw_list if all(val in word for val in keyword.split(' '))]

OUTPUT

['bank cd rates', 'bank rates', 'bank of america mortgage rates', 'bank exchange rates']
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