字符串的translate, maketrans方法讓人很迷惑,這里根據官方的__doc__研究了一下,限於英文水平,有些詞譯得可能
不太准確,歡迎交流!
Static methods defined here: | | 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. translate(...) | S.translate(table) -> str | | Return a copy of the string S in which each character has been mapped | through the given translation table. The table must implement | lookup/indexing via __getitem__, for instance a dictionary or list, | mapping Unicode ordinals to Unicode ordinals, strings, or None. If | this operation raises LookupError, the character is left untouched. | Characters mapped to None are deleted.
(x,y=None,z=None)如果只有x一個參數,那么它必須是一個字典,可以是unicode到字符,字符到unicode,字符串,
或者None, 並且key會轉成系數,如'a'的unicode會轉成97
''.maketrans({'a':'b'}) Out[30]: {97: 'b'} ''.maketrans({'c':97}) Out[37]: {99: 97}
其實這里轉成字符對應的系數沒什么作用,看下面的例子:
table = ''.maketrans({'t':97}) s = 'this is a test' s.translate(table) Out[43]: 'ahis is a aesa'
table = ''.maketrans({97:'t'}) s.translate(table) Out[48]: 'this is 97 test'
看到沒,還是只是完成了映射替換,並不會轉成數字,也就是說只是在生成table時轉換了(不知道為什么這么做,歡迎交流)
那如果目標字符串中有這個數字怎么辦呢?
table = ''.maketrans({97:'t'}) s.translate(table) Out[48]: 'this is 97 test'
可以看到,97並沒有被替換
如是給了兩個參數,x,y 必須是行長的字符串,結果會是字符,x,y中對應的位置形成映射,需要注意的是,
它並不是全字符串進行替換,你給定的字符串只反映了映射關系,並不能當作整體。它會一個一個的替換,看下面的例子:
s = 'this is a test' table = ''.maketrans('is', 'it') s.translate(table) Out[54]: 'thit it a tett'
最后面的s也被替換了
再看一個:
s = 'this is a test' table = ''.maketrans('test', 'joke') s.translate(table) Out[51]: 'ehik ik a eoke'
看到這里,你肯定又懵了,我去,t不應該映射成j嗎,怎么成了e,那是因為這里有兩個t,它應該是取的后面的一個
如果給了第三個參數,(第三個參數)它必須是字符串,這個字符串中的字符會被映射成None,簡單點說就是刪除了
s = 'this is a test' table = ''.maketrans('is', 'mn','h') s.translate(table) Out[57]: 'tmn mn a tent'
很明顯,第三個參數中的h 從最后結果中消失了,也就是刪除了。總的來說translate是非常強大的,不僅能替換,還能刪除。
那么這里還是有一個問題,當只給定一個參數時,字符雖然被成了系數(整數),最后並沒有被替換,那如果我要替換數字怎么辦?
s = 'this 996785433 9657576' table = ''.maketrans('945', 'ABC') s.translate(table) Out[60]: 'this AA678CB33 A6C7C76'
可以看到,指定兩個參數時,數字是可以正常 替換的。
所以,當指定一個參數時,是做不到這一點,因為只有一個參數時,字典的key長度只能為1.如果你替換數字,你至少得二個數字。
如有不妥,歡迎指正,交流。