當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python String translate()用法及代碼示例


translate()返回一個字符串,該字符串是根據給定的轉換映射修改為給定字符串的字符串。

有兩種翻譯方法:

提供映射作為字典

參數:


    string.translate(映射)

  • mapping-在兩個字符之間有映射的字典。
    返回:返回修改後的字符串,其中每個字符根據提供的映射表映射到其對應的字符。
# Python3 code to demostrate  
# translations without  
# maketrans()  
  
# specifying the mapping  
# using ASCII  
table = { 119 :103, 121 :102, 117 :None }  
  
# target string  
trg = "weeksyourweeks"
  
# Printing original string  
print ("The string before translating is:", end ="")  
print (trg)  
  
# using translate() to make translations.  
print ("The string after translating is:", end ="")  
print (trg.translate(table)) 
輸出:
The string before translating is:weeksyourweeks
The string after translating is:geeksforgeeks

再舉一個例子:

# Python 3 Program to show working 
# of translate() method 
  
# specifying the mapping   
# using ASCII   
translation = {103:None, 101:None, 101:None} 
  
string = "geeks"
print("Original string:", string) 
  
# translate string 
print("Translated string:",  
       string.translate(translation))
輸出:
Original string:geeks
Translated string:ks
使用提供映射maketrans()

Syntax:maketrans(str1, str2, str3)
Parameters:
str1:Specifies the list of characters that need to be replaced.
str2:Specifies the list of characters with which the characters need to be replaced.
str3:Specifies the list of characters that needs to be deleted.

Returns:Returns the translation table which specifies the conversions that can be used by translate()

# Python 3 Program to show working 
# of translate() method 
  
# First String 
firstString = "gef"
  
# Second String 
secondString = "eks"
  
# Third String 
thirdString = "ge"
  
# Original String 
string = "geeks"
print("Original string:", string) 
  
translation = string.maketrans(firstString,  
                               secondString,  
                               thirdString) 
  
# Translated String 
print("Translated string:",  
       string.translate(translation))
輸出:
Original string:geeks
Translated string:ks

輸出:

Original string:geeks
Translated string:ks


相關用法


注:本文由純淨天空篩選整理自Akanksha_Rai大神的英文原創作品 Python | String translate()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。