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

Asked

Viewed 388 times

2

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

Note: Use of FOR or FUNCTION is not allowed and without DICTIONARY.

Example:

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

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

  • 1

    Create your Function that does it the way you want to !!! And why can’t use it FOR ???

  • You can’t use function or for. It’s a challenge.

1 answer

8

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

entrada = "Bolacha"

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

saida = entrada.translate( tabela )

print(saida)

Or:

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

Exit:

Buleche

Browser other questions tagged

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