# Does Mathematica have an equivalent to the Python 'translate' function?

In Python you can make a character translation table with 'maketrans', passing it two strings of the same length. Then you can call 'translate' passing a new string and the table you just created. The function will map characters in the input string using the table you created with 'maketrans'.

Is there an easy way to do this in Mathematica without using a long list of rules or an Association?

\$Version

(* "13.1.0 for Mac OS X x86 (64-bit) (June 16, 2022)" *)

Clear["Global*"]

maketrans[str1_String, str2_String] :=
Rule @@@ Thread[Characters /@ {str1, str2}] /;
Equal @@ (StringLength /@ {str1, str2})

alphabet = CharacterRange["a", "z"];

str1 = StringJoin@alphabet;

SeedRandom[1234];

str2 = StringJoin@RandomSample[alphabet];

rules = maketrans[str1, str2];

garble = StringReplace["this is an example", rules]

(* "krex ex bi znbcthz"  *)


Undo translation

StringReplace[garble, Reverse /@ rules]

(* "this is an example" *)

• Nicely done! I was hoping for some Mathematica builtin function that would do the work of maketrans, but this is a very nice solution, although it ultimately involves "a long list of rules" (see problem statement). Commented Nov 17, 2022 at 20:41
• The list of rules is "the table". The form of the table is immaterial; you are still just doing a form of table lookup. Commented Nov 17, 2022 at 21:37

Python String maketrans() Method

Python code:

txt = "Hi Sam!"

x = "mSa"
y = "eJo"

mytable = txt.maketrans(x, y)

print(txt.translate(mytable))


Mathematica code:

txt = "Hi Sam!"

x = "mSa";
y = "eJo";

StringReplace[txt, Thread[Characters /@ (x -> y)]]

Clear[x, y, txt]

(* "Hi Sam!" *)
(* "Hi Joe!" *)
`