我对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, ' ')
反正有吗?
答案 0 :(得分:1)
在Python3中, deletechars 被添加为maketrans
的第三个参数,而不是translate
的第二个参数。在这两种情况下,当手动创建一个unicode映射字典以传递给None
时,字符可以映射到maketrans
# Python3
table = str.maketrans ('cs', 'kz', ' ')
"this is an incredible test".translate(table)
给出: ' thizizaninkredibletezt'