Python Forum

Full Version: Create a new list by comparing values in a list and string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have elements in a predefined list and a query string.  I would like to check if the query_str has any values in predefined list and if so, append them to a new list as separate elements.

predefined_lst = ['hello', 'goodbye', 'see you later']
query_str  = 'hello | are you having a nice day?  see you later |'
new_lst = [ ]
I have the syntax to compare the string to the values in the list, but I can't get the values that appear in the string to append to the new list as individual elements in the list.
In the example above, new_lst should be
new_lst = ['hello', 'see you later']
What I have now just results in True when I print new_lst.  Thanks for any help


new_list = []
match = if any(string in query_str for string in predefined_lst)
new_lst.append(match)
print(new_lst)
tips
1. any return true or false.
this is a true and false statement.
string in query_str
so if you remove if any.
it returns a generator of true and false
(string in query_str for string in predefined_lst)
2. write it out long hand. avoid the expression.
predefined_lst = ['hello', 'goodbye', 'see you later']
query_str = 'hello | are you having a nice day?  see you later |'
new_lst = [string for string in predefined_lst if string in query_str]
print(new_lst)
Output:
['hello', 'see you later']