How to check if part of a string is contained in a Python list?

Asked

Viewed 3,100 times

0

I am writing a Python3 script, in order to place a filter to prevent the user from passing a string containing an offensive or improper word.

So I created a list containing the words I want to put this filter in and then I treated them with the operators not in and in and when the condition not in is met want to continue the script execution and when the condition in is met want to return the execution alerting the user that the string passed by it contains an offensive word

I even managed to make the script work, but only when the string passed is == to the value contained in the list.

I wanted to make this filter more complete by analyzing all the text and if a part of the string contains the value contained in the list, I wanted the script to also execute the instruction code block in

Below I’m putting the script:

class Textoofencivo():

     def verifica():

            texto = input('Digite um texto: ').strip()

            texto_formatado = texto.upper()

            my_list = [
            "AAA", "BBB"
            ]

            iniciar = None
            while(iniciar == None):

                    if(texto_formatado not in my_list):
                            print('\n' * 1)
                            print('Bem Vindo')
                            print('\n' * 1)
                            ###### CONTINUA O SCRIPT #####
                            break

                    elif(texto_formatado  in list(my_list)):
                            print('\n' * 1)
                            print('O texto informado contem uma 
                            palavra ofensiva\nRetornando a Execução')
                            print('\n' * 1)
                            ###### RETORNA A EXECUÇÂO ANTERIOR ######
                            texto = None
                            return TextoOfencivo.verifica()                       

Textoofencivo.()

Can someone help me ? Thank you in advance!!!

Sincerely yours truly, Michael de Mattos

1 answer

1

Just you check with the operator in if the strings inside the list then inside its text, traversing the list with a for loop and using the method lower() so that there are no differences between upper and lower case. See this example I did:

def verifica(texto, palavrasProibidas):

    for palavra in palavrasProibidas:
        if palavra.lower() in texto.lower():
            return False
    return True


palavrasProibidas = ["c05n0","v4g4bund0","@rr0mbad0","v1@do"]
texto = input("Digite o texto: ")


if verifica(texto, palavrasProibidas):
    print("O texto não possui palavras ofensivas")

else:
    print("O texto possui palavras ofensivas.")

Maybe you don’t know this, but the operator in can be used on any object that has the method __contains__, such as strings, lists, tuples, dictionaries and others, to check if an element is present in it.

What you did was check if the raw string was inside the list (str in list), when you should check if any string from the list was inside the text with a substring (str in str).

  • Thank you very much! Solved my problem and the explanation was note 10.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.