python提取部分字符串三参数_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返回一個(gè)給translate用的映射表,translate根據(jù)映射表構(gòu)造新的字符串。
makestran根據(jù)參數(shù)的個(gè)數(shù)有三種使用方法:
1)一個(gè)參數(shù)情況,參數(shù)必須是字典
一個(gè)字符轉(zhuǎn)換成一個(gè)字符
1 >>> a='qwerabc2348'
2 >>> d={'a':'A','q':'Q'} #轉(zhuǎn)換映射表3 >>> tans=str.maketrans(d) #轉(zhuǎn)換為translate可以使用的映射表4 >>>tans5 {97: 'A', 113: 'Q'} #translate可以使用的映射表6 >>>a.translate(tans)7 'QwerAbc2348' #轉(zhuǎn)換后的結(jié)果
一個(gè)字符轉(zhuǎn)換為多個(gè)字符
1 >>> d2={'a':'*A*','q':'*Q*'}2 >>> tans2=str.maketrans(d2)3 >>>tans24 {97: '*A*', 113: '*Q*'}5 >>>a.translate(tans2)6 '*Q*wer*A*bc2348
一個(gè)字符轉(zhuǎn)換為None,效果為過(guò)濾刪除字符
1 >>> d3={'a':None,'q':None}2 >>> tans3=str.maketrans(d3)3 >>>tans34 {97: None, 113: None}5 >>>a.translate(tans3)6 'werbc2348'
2)兩個(gè)參數(shù)的情況,參數(shù)(字符串)必須長(zhǎng)度相等。
1 >>> a='acbsdwf124'
2 >>> tans4=str.makestrans('abc','ABC')3 >>> tans4=str.maketrans('abc','ABC')4 >>>tans45 {97: 65, 98: 66, 99: 67}6 >>>a.translate(tans4)7 'ACBsdwf124'
3)三個(gè)參數(shù)的情況,前兩個(gè)參數(shù)效果和2)相同,第三個(gè)參數(shù)為要過(guò)濾刪除的字符表(第三個(gè)參數(shù)都映射為None)
1 >>>a2 'acbsdwf124'
3 >>> tans5=str.maketrans('abc','ABC','1234')4 >>>tans55 {97: 65, 98: 66, 99: 67, 52: None, 51: None, 49: None, 50: None}6 >>>a.translate(tans5)7 'ACBsdwf'
4)映射表中的數(shù)字為unicode編碼數(shù)字
1 >>> ord('a')2 97
3 >>> chr(97)4 'a'
總結(jié)
以上是生活随笔為你收集整理的python提取部分字符串三参数_python3 字符串属性(三)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 某中学要对学校运动会进行计算机管理,20
- 下一篇: 和移动对接短信http协议和cmpp协议