使用string.makestrans()
时,可以创建一个逐字工作的翻译表。
例如,此翻译表将每个字母移动到两个位置:
import string
intab = "abcdefghijklmnopqrstuvwxyz"
outtab = "cdefghijklmnopqrstuvwxyzab"
translationtable = string.maketrans(intab, outtab)
如果我有一个需要翻译的值列表呢?
intab = [`TBA', 'RIP', TGIF', 'FAQ']
outtab = ['To Be Announced', 'Rest In Peace',
'Thank God It\'s Friday', 'Frequently Asked Questions']
翻译这种东西的标准方法是什么?
最佳答案
您可以使用zip
创建对,使用dict
创建“转换器”(字典):
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'}