Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Character translation in Python

📅 2012-May-04 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ python, translation ⬩ 📚 Archive

Python has a couple of functions that make it easy to replace characters in a string with other characters. bytes.maketrans() is used to create the translation table. string.translate() uses this table to replace the matching characters in the string with their replacements in the table.

# Replace 'a' with '1', 'b' with '2' and 'c' with '3'

table = bytes.maketrans( b"abc", b"123" )
s     = "abracadabra"
s2    = s.translate( table )
print( s2 ) # 12r131d12r1

Tried with: Python 3.2


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧