Python 字串 translate() 方法



Python 字串translate() 方法是字串模組中maketrans() 方法的後續方法。此方法使用maketrans() 方法生成的轉換表,並根據該表中的一對一對映轉換所有字元。

此方法的轉換表輸入在建立索引時執行以下任何操作:

  • 它可用於檢索字串或 Unicode 序號。
  • 它將一個字元對映到一個或多個其他字元。
  • 它可以從檢索到的字串中刪除一個字元。
  • 如果將字元對映到自身,則會引發LookUpError

注意 - 它與文字檔案中的替換函式類似。

語法

以下是 Python 字串translate() 方法的語法:

str.translate(table);

引數

  • table - 你可以使用字串模組中的 maketrans() 輔助函式來建立轉換表。

返回值

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

示例

使用此方法,字串中的每個母音都將替換為其母音位置。

以下示例演示了 Python 字串 translate() 方法的用法。在這裡,我們建立兩個字串:“aeiou”和“12345”。我們首先使用 maketrans() 方法根據這些字串輸入生成轉換表。然後,我們呼叫生成的轉換表上的 translate() 方法,以獲取最終字串。

intab = "aeiou"
outtab = "12345"

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

執行上述程式時,會產生以下結果:

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

示例

我們建立一個字典作為轉換表,並將其作為引數傳遞給該方法,以獲得已轉換的字串作為返回值。

在下面的例子中,我們建立一個字串輸入,例如“this is string example....wow!!!”,以及一個作為Python字典的翻譯表。`translate()` 方法被呼叫在輸入字串上,翻譯表作為引數傳遞。

trantab = {97: 65, 101: 69, 105: 73, 111: 79, 117: 86}

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

執行上面的程式將產生以下結果:

thIs Is strIng ExAmplE....wOw!!!

示例

另一個例子演示了 `translate()` 方法的用法,如下所示。我們取一個字串“Here, affect is noun”和一個Python字典作為輸入。`translate()` 方法將字典作為引數,並被呼叫在我們建立的輸入字串上。

trantab = {97: 101}

str = "Here, affect is noun"
print(str.translate(trantab))

如果我們編譯並執行上面的程式,則會產生如下輸出:

Here, effect is noun
python_strings.htm
廣告