One of the coolest things: .translate() and str.maketrans() in Python

One of the coolest things: .translate() and str.maketrans() in Python

I just learned about the translate() and str.maketrans() methods in Python.

This is absolutely one of the coolest things that I have ever learned. I think about it in two parts.

str.maketrans() allows you to make a table of sorts (A TABLE, I know!!! Crazy, huh? Where was that in JavaScript??) and that is your translation table or comparison table so to speak. So imagine I wanted to translate "pink" to "blue"; I could create a table like this (in any order):

maketrans("knpi", "eubl")

and that creates a table that makes out something like this:

k -> e

n -> u

p -> b

i -> l


and then you could have in the code:

color = pink

new_color = color.translate(str.maketrans("knpi", "eubl"))

print(new_color) # Output: blue
Pink and yellow background. Images of DNA and a computer: two yellow post its read ".translate() and str.maktrans()". build up tables and translate your strings across!
This is WONDERFUL and this is one of the craziest and coolest things that I have ever learned in my life.

p.s. the image of the DNA came from the fact that I learned this method while I was doing the Complementary DNA Codewars challenge and looking at the solution: https://www.codewars.com/kata/554e4a2f232cdd87d9000038

Wow, thank you so so much, wow!!

Comments