Python字串title()方法

Python字串translate()方法返回使用表(使用string模組中maketrans()函數構造)轉換了所有字元的字串的副本),可選地刪除字串deletechars中的所有字元。

語法

以下是translate()方法的語法 -

str.translate(table[, deletechars]);

參數

  • table - 可以在string模組中使用maketrans()函數來創建一個轉換表。

返回值

  • 此方法返回字串的轉換副本。

示例

以下示例顯示了translate()方法的用法。在這種情況下,字串中的每個母音都被其母音位置所取代 -

#!/usr/bin/python3

from string import maketrans # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print (str.translate(trantab))

當運行上面的程式,它產生以下結果 -

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

示例2

以下是從字串中刪除“x”和“m”個字元的示例:

#!/usr/bin/python3

from string import maketrans   # Required to call maketrans function.

intab = "aeiouxm"
outtab = "1234512"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print (str.translate(trantab))

當運行上面的程式,它產生以下結果 -

th3s 3s str3ng 21pl2....w4w!!!

上一篇: Python字串 下一篇: Python列表