Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display element of a list detected by "if any"

I'm using a simple system to check if some banned words are currently in a string but I'd like to improve it to display the word in question so I added the line

print ("BANNED WORD DETECTED : ", word)

But I get the error

"NameError: name 'word' is not defined"

If think that the problem is that my system is just checking if any of the words is in the list without "storing it" somewhere, maybe I am misunderstanding the python list system, any advice of what I should modify ?

# -*- coding: utf-8 -*-

bannedWords = ['word1','word2','check']
mystring = "the string i'd like to check"

if any(word in mystring for word in bannedWords):
    print ("BANNED WORD DETECTED : ", word)
else :
    print (mystring)

1 Answers

any() isn't suitable for this, use a generator expression with next() instead or a list comprehension:

banned_word = next((word for word in mystring.split() if word in bannedWords), None)
if banned_word is not None:
   print("BANNED WORD DETECTED : ", word)

Or for multiple words:

banned_words = [word for 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 a set rather than a list

like image 96
Chris_Rands Avatar answered Jan 21 '26 00:01

Chris_Rands