string 中的maketrans和translate

时间:2023-01-30 10:52:04

maketrans 和 translate 是 Python 内置的 string 包中的两个类似于密码本的方法,一般来说,使用 translate 前需要先制作一个 maketrans 的 “密码本”(table)。


#仅支持python2,python3废弃了该方法,不过可以使用bytes.translate, bytes.maketrans来代替,然后再转换回去
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,因为str 中废弃了 maketranstanslate ,因此我们只能通过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'