Home > Back-end >  How to switch out more than one pair of letters at once in a string?
How to switch out more than one pair of letters at once in a string?

Time:01-12

I switched out one pair of letters with maketrans, but I don't know to what to do if I wanted to switch more letters at the same time.

For example change the "a" to a "z". I know I can use .replace, but I don't know if that does it for all of the "a" in the string.

string = "Hello Sam!"

print(string.translate(string.maketrans("S", "P")))

CodePudding user response:

str.maketrans() supports parameters of longer than a single character. They represent the one for one translation.

string = "Hello Sam!"
from_characters = "Sl"
to_characters   = "P$"
translator = str.maketrans(from_characters, to_characters)
print(string.translate(translator ))

Gives you:

He$$o Pam!

  • Related