How to work with more than one replacement in Python using Replace?

2

How to work with more than one replacement in Python using Replace?

Note: The use of FOR or FUNCTION is not allowed without DICTIONARY.

Example:

print("Bolacha".replace('a', 'e').replace('o', 'u'))

How to improve the above code without having to keep repeating .replace ....?

    
asked by anonymous 01.07.2018 / 12:44

1 answer

8

In Python 3 , the primitive type str provides interface for this. You can create a translation table using the static method str.maketrans() and then perform the override operation using the str.translate() :

entrada = "Bolacha"

tabela = str.maketrans( 'ao', 'eu' )     

saida = entrada.translate( tabela )

print(saida)

Or:

print("Bolacha".translate( str.maketrans( 'ao', 'eu' )))

Output:

Buleche
    
01.07.2018 / 13:30