I have a list of strings
BAD_STRINGS = ['change of director interest notice', 'change of directors interest notice', 'dividend reinvestment plan allocation price']
I want to loop over the bad strings and check if any of them are found anywhere in my USER_INPUT_STRING, the bad strings should be matched only if they are present in their entirety and in order. ( ie don't just match the words ... they must be as presented in order ) the bad string can appear anywhere in the user input string.
USER_INPUT_STRING = "interest love horses change of director house price"
#should return false
USER_INPUT_STRING = "i walked in the part and change of directors interest notice house price"
#should return true
I have tried to use .find
and the [USER_INPUT_STRING in BAD_STRINGS do xyz]
methods but keep getting weird results, it appears those methods are just checking if the words appear in any order instead of checking if the whole string is found in order.
Any help is appreciated i've been stuck on this the whole day.
CodePudding user response:
You need to loop over BAD_STRINGS
to test each of them. Use the any()
function to return true if any of them match.
any(bad in USER_INPUT_STRING for bad in BAD_STRINGS)
CodePudding user response:
import re
BAD_STRINGS = ['change of director interest notice', 'change of directors interest notice', 'dividend reinvestment plan allocation price']
USER_INPUT_STRING = "i walked in the part and change of directors interest notice house price"
for words in BAD_STRINGS:
if re.search(r'\b' words r'\b', USER_INPUT_STRING):
print('{0} found'.format(words))
An alternative way using regular expressions. In case it appears, you can do operations as needed.