When using string.makestrans()
, you create a translation table which works character by character.
For example, this translation table moves each letter over two place:
import string
intab = "abcdefghijklmnopqrstuvwxyz"
outtab = "cdefghijklmnopqrstuvwxyzab"
translationtable = string.maketrans(intab, outtab)
What if I have a list of values which I need to translate?
intab = [`TBA', 'RIP', TGIF', 'FAQ']
outtab = ['To Be Announced', 'Rest In Peace',
'Thank God It\'s Friday', 'Frequently Asked Questions']
What is the standard way to translate something like this?
You can use zip
to create the pairs and dict
to create the "translator" (dictionary):
intab = ['TBA', 'RIP', 'TGIF', 'FAQ']
outtab = ['To Be Announced', 'Rest In Peace',
'Thank God It\'s Friday', 'Frequently Asked Questions']
translationtable = dict(zip(intab, outtab))
# {'TBA': 'To Be Announced', 'TGIF': "Thank God It's Friday", 'FAQ': 'Frequently Asked Questions', 'RIP': 'Rest In Peace'}