translate()返回一个字符串,该字符串是根据给定的转换映射修改为给定字符串的字符串。
有两种翻译方法:
提供映射作为字典
参数:
mapping
-在两个字符之间有映射的字典。
返回:返回修改后的字符串,其中每个字符根据提供的映射表映射到其对应的字符。
string.translate(映射)
# 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
相关用法
- Numpy string translate()用法及代码示例
- Python Pandas Series.str.translate()用法及代码示例
- Python maketrans() and translate()用法及代码示例
注:本文由纯净天空筛选整理自Akanksha_Rai大神的英文原创作品 Python | String translate()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。