Python
——
maketrans
和
translate
方法
最近在看
Python
Cookbook
,发现无法理解字符串处理的两个方法
maketrans,
translate
,在
Python
解释器里面查看说明文档也语焉不详,莫名其妙,结合网上看到的一些说明,这里
以比较容易理解的方式来解释一下这两个方法,算是对官方文档的一些注解。
maketrans
和
translate
是密切相关的两个方法,先看
translate
的说明
S.translate(table [,deletechars]) -> string
Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256.
简单来说就是对字符串
S
移除
deletechars
包含的字符,
然后保留下来的字符按照
table
里面
的字符映射关系映射
(比如
a
变成
A
,
后面会解释到)
。
那个莫名其妙的
"which must be a string
of
length
256"
就不用深究了,反正
table
就是由
string.maketrans
方法生成的,对于
string.maketrans
方法,这里有个更清晰的解释
,
如下:
string.maketrans(intab,
outtab)
-->
This
method
returns
a
translation
table
that
maps
each
character in the intab string into the character at the same position in the outtab string. Then this
table is passed to the translate() function. Note that both intab and outtab must have the same
length.
下面是一些实例说明:
import string
s = 'abcdefg-1234567'
table = string.maketrans('', '') #
没有映射,实际上就是按原始字符保留,看下面用到
translate
中时的效果
s.translate(table)
#
输出
abcdefg-1234567
s.translate(table, 'abc123') #
输出
defg-4567
可以看到删除了字符
abc123
#
下面再看有字符映射时的效果
table = string.maketrans('abc', 'ABC') #
用于
translate
中时的效果如下
s.translate(table)
#
输出
ABCdefg-1234567
就是将
abc
映射为大写的
ABC
,前提是
abc
如果被
保留下来了
s.translate(table, 'ab123') #
输出
Cdefg-4567
先把
s
中的
ab123
去除了,然后在保留下来的字
符中应用
table
中指定的字符映射关系映射:
c -> C