It is also possible to remove unwanted characters without using regular expressions.
The class str contains the method str.translate()
which returns a copy of the string in which each character was mapped through the translation table created with the static method str.maketrans()
whose one of its implementation accepts two parameters that must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y.
texto = "João:saiu!! de%$ˆcasa" #Texto a ser purgado.
indesejados = ":!%$ˆ" #Caracteres a serem purgados.
tabela = str.maketrans(indesejados, " " * len(indesejados)) #Cria a tabela de tradução onde cada caractere indesejado será mapeado para um caractere de espaço.
novo_texto = " ".join(texto.translate(tabela).split()) #Purga o texto, o descontrói e o reconstrói sem espaços duplicados.
print(novo_texto) #Imprime João saiu de casa
Test the example on ideone.