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 to add condition (wildcard search) for this for loop in an f-string?

Got a piece of code here that is trying to insert "i" into this f string during a for loop. However, I want python to filter this out based on whether ‘i’ contains a certain string (‘nogood’). I noticed it works with ‘=’ or ‘in’ but NOT ‘like’. I’ve tried the following but it doesn’t compile…

i_list = ['hello', 'good', 'bad', 'bye', 'yup', 'yupnogood', 'hellogood']
final_list = [f"{i}_hello" for i in temp_list if i like '%good%']

Do you know if there is a shorthand way to get the wildcard search implemented in there? or is this not good practice?

Thanks in advance.

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 :

For this simple form of wildcard search, you can use the in operator:

i_list = ['hello', 'good', 'bad', 'bye', 'yup', 'yupnogood', 'hellogood']
final_list = [f"{i}_hello" for i in temp_list if 'nogood' in i]

If you want something more complex, you could look into regular expressions.

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