maketrans 和 translate 是 Python 内置的 string 包中的两个类似于密码本的方法,一般来说,使用 translate 前需要先制作一个 maketrans 的 “密码本”(table)。
# ---------------------此处有误-----------------------------------
#仅支持python2,python3废弃了该方法,不过可以使用bytes.translate, bytes.maketrans来代替,然后再转换回去
# ------------针对python3---------------
# python3 中由内置函数str.translate, str.maketrans 代替了,不需要导入string再转换
import string
from string import punctuation #导入标点符号集
In [1]: punctuation
Out[1]: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
#先制定一个对应的密码表,将标点符号转成相同长度的空格
In [2]: table = string.maketrans(punctuation, ' '*len(punctuation))
In [2]: sentence = 'I come from China, hello world! hi.'
#根据制定的密码表开始 translate
In [3]: sentence.translate(table)
Out[3]: 'I come from China hello world hi '
#可选参数为 deletions(删除项)
#python 3中只接受table项,不在有可续参数了,这个神烦~
In [4]: sentence.translate(table,' ')
Out[4]: 'IcomefromChina helloworld hi '
In [5]: string.translate(sentence, table)
Out[5]: 'I come from China hello world hi '
In [6]: string.translate(sentence, table, ' ')
Out[6]: 'IcomefromChina helloworld hi '
#这个比较常用(密码表设置为None,后一个参数设置为要删除的对象)
In [7]: sentence.translate(None, punctuation)
Out[7]: 'I come from China hello world hi'
如果是Python3,我们可以通过bytes
进行该操作(这个转换看着比较繁琐,其实不用这么做),举例如下:
In [58]: from datetime import datetime
...:
...: def parse_datetime(dt):
...: strd = str(dt)
...: table = bytes.maketrans(b'-:.', b'___')
...: return str(bytes(strd, encoding='utf-8').translate(table), encoding='utf-8')
...:
In [59]: parse_datetime(datetime.now())
Out[59]: '2018_02_08 11_42_52_360683'
或者python3 使用str
即可:
In [72]: table = str.maketrans('abcde', '12345')
In [73]: 'just for test, a b c, please'.translate(table)
Out[73]: 'just for t5st, 1 2 3, pl51s5'