I am having some trouble figuring out how to replace multiple characters in a string.I am trying to write a functions called replace(string) that takes in an input, and replaces certain letters in the input with another letter.
Lets say I have the string "WXYZ" and I want to replace all the W with Y, X with Z, Y with W, and Z with X. I want it to do the replacement no matter what the input is. so if I also do something like replace("WWZXWWXYYZWYYY") it should replace the letters like I said above.
This is what I have done so far:
for letters in string:
string = string.replace("W","Y").replace("X","Z").replace("Y","W").replace("Z","X")
Note that your calls are structured in such a way that
W is replaced with
Y in the first call, and then
Y is again replaced with
W in the third call, undoing the first call's output.
You should be using
str.translate, it's much more efficient and robust than a bunch of chained
_tab = str.maketrans(dict(zip('WXYZ', 'YZWX'))) def replace(string): return string.translate(_tab)
>>> replace('WXYZ') 'YZWX' >>> replace("WWZYWXXWYYZW") 'YYXWYZZYWWXY'