Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I am new to programming in general, and couldn't figure out how to replace multiple characters in a string. Using the string.replace("x", "y") function, I tried to make a simple encoder:

phrase = "abcdef"

phrase.replace("a", "b")

phrase.replace("b", "c")

phrase.replace("c", "d")

phrase.replace("d", "e")

phrase.replace("e", "f")

phrase.replace("f", "g")

print(phrase)

I was expecting the output to be:

"bcdefg"

but instead got

"abcdef"

This was best I could come up with and it does not work. I looked around other questions and the answers were too confusing. Please help and explain what i am doing wrong.

1 Answer

0 votes
by (25.1k points)

In python 3 we can use str.maketrans and then str.translate, like this:

trans = str.maketrans("abcdef","bcdefg") 

phrase = "abcdef" print(str.translate(phrase, trans))

Related questions

Browse Categories

...