I have a piece of code that is trying to insert 'i'
into an 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 (if it is good practice to do so)?
CodePudding user response:
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.