python3 字符串属性(三)

maketrans 和 translate的用法(配合使用)

下面是python的英文用法解释

maketrans(x, y=None, z=None, /)
Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then 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

 

S.translate(table) -> str

Return a copy of the string S, where all characters have been mapped
through the given translation table, which must be a mapping of
Unicode ordinals to Unicode ordinals, strings, or None.
Unmapped characters are left untouched. Characters mapped to None
are deleted.

makestans返回一个给translate用的映射表,translate根据映射表构造新的字符串。

makestran根据参数的个数有三种使用方法:

1)一个参数情况,参数必须是字典

一个字符转换成一个字符

1 >>> a='qwerabc2348'     
2 >>> d={'a':'A','q':'Q'}     #转换映射表
3 >>> tans=str.maketrans(d)  #转换为translate可以使用的映射表
4 >>> tans
5 {97: 'A', 113: 'Q'}     #translate可以使用的映射表
6 >>> a.translate(tans)
7 'QwerAbc2348'    #转换后的结果

 

 

一个字符转换为多个字符

1 >>> d2={'a':'*A*','q':'*Q*'}
2 >>> tans2=str.maketrans(d2)
3 >>> tans2
4 {97: '*A*', 113: '*Q*'}
5 >>> a.translate(tans2)
6 '*Q*wer*A*bc2348

 

 

一个字符转换为None,效果为过滤删除字符

1 >>> d3={'a':None,'q':None}
2 >>> tans3=str.maketrans(d3)
3 >>> tans3
4 {97: None, 113: None}
5 >>> a.translate(tans3)
6 'werbc2348'

 

2)两个参数的情况,参数(字符串)必须长度相等。

1 >>> a='acbsdwf124'
2 >>> tans4=str.makestrans('abc','ABC')
3 >>> tans4=str.maketrans('abc','ABC')
4 >>> tans4
5 {97: 65, 98: 66, 99: 67}
6 >>> a.translate(tans4)
7 'ACBsdwf124'

 

 

3)三个参数的情况,前两个参数效果和2)相同,第三个参数为要过滤删除的字符表(第三个参数都映射为None)

1 >>> a
2 'acbsdwf124'
3 >>> tans5=str.maketrans('abc','ABC','1234')
4 >>> tans5
5 {97: 65, 98: 66, 99: 67, 52: None, 51: None, 49: None, 50: None}
6 >>> a.translate(tans5)
7 'ACBsdwf'

 

 

4)映射表中的数字为unicode编码数字

1 >>> ord('a')
2 97
3 >>> chr(97)
4 'a'

 

posted @ 2016-03-11 20:44  hb91  阅读(437)  评论(0编辑  收藏  举报