python 2和3之间在"翻译"方面的差异

时间:2014-05-21 22:04:12

标签: python

我对python 3中的翻译功能有疑问 (我正在读一本关于python 2的书)

在Python2中,我们这样做:

from string import maketrans 
table = maketrans ('cs', 'kz')

"this is an incredible test".translate(table)
"this is an incredible test".translate(table, ' ')

我们如何在python 3中完成它?我知道:

table = str.maketrans ('cs', 'kz')
"this is an incredible test".translate(table)

将有效

但我似乎无法弄清楚如何做到:

"this is an incredible test".translate(table, ' ')

反正有吗?

1 个答案:

答案 0 :(得分:1)

在Python3中, deletechars 被添加为maketrans的第三个参数,而不是translate的第二个参数。在这两种情况下,当手动创建一个unicode映射字典以传递给None时,字符可以映射到maketrans

# Python3
table = str.maketrans ('cs', 'kz', ' ')
"this is an incredible test".translate(table)

给出: ' thizizaninkredibletezt'

相关问题