天天看點

python3 translate_python3 字元串的 maketrans,translate 方法詳解

字元串的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.如果你替換數字,你至少得二個數字。

如有不妥,歡迎指正,交流。