📜  Python|字符串翻译()

📅  最后修改于: 2022-05-13 01:54:52.991000             🧑  作者: Mango

Python|字符串翻译()

translate()根据给定的翻译映射返回一个字符串,该字符串是给定字符串的修改字符串。

有两种翻译方式:

提供映射作为字典

参数 :

# Python3 code to demonstrate 
# 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() 提供映射
# 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