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返回一個給translate用的映射表,translate根據映射表構造新的字符串。
makestran根據參數的個數有三種使用方法:
1)一個參數情況,參數必須是字典
一個字符轉換成一個字符
1 >>> a='qwerabc2348'
2 >>> d={'a':'A','q':'Q'} #轉換映射表3 >>> tans=str.maketrans(d) #轉換為translate可以使用的映射表4 >>>tans5 {97: 'A', 113: 'Q'} #translate可以使用的映射表6 >>>a.translate(tans)7 'QwerAbc2348' #轉換后的結果
一個字符轉換為多個字符
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
一個字符轉換為None,效果為過濾刪除字符
1 >>> d3={'a':None,'q':None}2 >>> tans3=str.maketrans(d3)3 >>>tans34 {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 >>>tans45 {97: 65, 98: 66, 99: 67}6 >>>a.translate(tans4)7 'ACBsdwf124'
3)三個參數的情況,前兩個參數效果和2)相同,第三個參數為要過濾刪除的字符表(第三個參數都映射為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)映射表中的數字為unicode編碼數字
1 >>> ord('a')2 97
3 >>> chr(97)4 'a'
總結
以上是生活随笔為你收集整理的python提取部分字符串三参数_python3 字符串属性(三)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 某中学要对学校运动会进行计算机管理,20
- 下一篇: websocket python爬虫_p