python - Display element of a list detected by "if any" -
i'm using simple system check if banned words in string i'd improve display word in question added line
print ("banned word detected : ", word)
but error
"nameerror: name 'word' not defined"
if think problem system checking if of words in list without "storing it" somewhere, maybe misunderstanding python list system, advice of should modify ?
# -*- coding: utf-8 -*- bannedwords = ['word1','word2','check'] mystring = "the string i'd check" if any(word in mystring word in bannedwords): print ("banned word detected : ", word) else : print (mystring)
any()
isn't suitable this, use generator expression next()
instead or list comprehension:
banned_word = next((word word in mystring.split() if word in bannedwords), none) if banned_word not none: print("banned word detected : ", word)
or multiple words:
banned_words = [word word in mystring.split() if word in bannedwords] if banned_words: print("banned word detected : ", ','.join(banned_words))
for improved o(1) membership testing, make bannedwords
set
rather list
Comments
Post a Comment