Python3 translate()方法

Python3 字串 Python3 字串


描述

translate() 方法根據參數table給出的表(包含 256 個字元)轉換字串的字元,要過濾掉的字元放到 deletechars 參數中。

語法

translate()方法語法:

str.translate(table)
bytes.translate(table[, delete])
bytearray.translate(table[, delete])

參數

  • table -- 翻譯表,翻譯表是通過 maketrans() 方法轉換而來。
  • deletechars -- 字串中要過濾的字元列表。

返回值

返回翻譯後的字串,若給出了 delete 參數,則將原來的bytes中的屬於delete的字元刪除,剩下的字元要按照table中給出的映射來進行映射 。

實例

以下實例展示了 translate() 函數的使用方法:

實例(Python 3.0+)

#!/usr/bin/python3 intab = "aeiou" outtab = "12345" trantab = str.maketrans(intab, outtab) # 製作翻譯表 str = "this is string example....wow!!!" print (str.translate(trantab))

以上實例輸出結果如下:

th3s 3s str3ng 2x1mpl2....w4w!!!

以下實例演示如何過濾掉的字元 o:

實例(Python 3.0+)

#!/usr/bin/python # 製作翻譯表 bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ') # 轉換為大寫,並刪除字母o print(b'zaixian'.translate(bytes_tabtrans, b'o'))

以上實例輸出結果:

b'RUNB'

Python3 字串 Python3 字串