I need to replace some characters as follows: & ➔ \\&, # ➔ \\#, ...
I coded as follows, but I guess there
Late to the party, but I lost a lot of time with this issue until I found my answer.
Short and sweet, translate is superior to replace. If you're more interested in funcionality over time optimization, do not use replace.
Also use translate if you don't know if the set of characters to be replaced overlaps the set of characters used to replace.
Case in point:
Using replace you would naively expect the snippet "1234".replace("1", "2").replace("2", "3").replace("3", "4") to return "2344", but it will return in fact "4444".
Translation seems to perform what OP originally desired.