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?


2 Answers 2


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


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

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

str1 = StringJoin@alphabet;


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" *)
  • $\begingroup$ 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). $\endgroup$
    – Jim Marks
    Commented Nov 17, 2022 at 20:41
  • $\begingroup$ The list of rules is "the table". The form of the table is immaterial; you are still just doing a form of table lookup. $\endgroup$
    – Bob Hanlon
    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)


Mathematica code:

txt = "Hi Sam!"

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

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

Clear[x, y, txt]

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.