static
str.
maketrans
(x[, y[, z]])This static method returns a translation table usable for
str.translate()
.If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or
None
. Character keys will then be converted to ordinals.If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to
None
in the result.
str.maketrans(x[,y[,z]])可返回用于str.translate()的转换表
如果只有一个参数,必须是一个字典
例:str.maketrans(x)
>>> d = {'a':'1','b':'2','c':'3','d':'4','e':'5','s':'6'}
>>> trantab = str.maketrans(d)
>>> st='just do it'
>>> print(st.translate(trantab))
'ju6t 4o it'
>>> d = {'a':'123','s':'456','d':'789'}
>>> trantab = str.maketrans(d)
>>> st='just do it'
>>> print(st.translate(trantab))
ju456t 789o it
>>> d = {'a':'123','s':'456','d':None}
>>> trantab = str.maketrans(d)
>>> st='just do it'
>>> print(st.translate(trantab))
ju456t o it
如果两个参数,x,y长度必须是相等的字符串,x中每个字符将映射到y中相同位置的字符
例:str.maketrans(x,y)
>>> x = 'abcdefs'
>>> y = '1234567'
>>> st='just do it'
>>> trantab = str.maketrans(x,y)
>>> print(st.translate(trantab))
ju7t 4o it
如果三个参数,第三个参数必须是个字符串,其字符将被映射为None
例:str.maketrans(x,y,z)
>>> x = 'abcdefs'
>>> y='1234567'
>>> z='ot'
>>> st='just do it'
>>> trantab = str.maketrans(x,y,z)
>>> print(st.translate(trantab))
ju7 4 i