Python中的 maketrans() 和 translate() 函数
在编程世界中,很少需要一次替换整个文件中的所有单词/字符Python使用函数 translate() 及其辅助函数 maketrans() 提供此功能。本文讨论了这两个函数。
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()
翻译字符中的字符串translate() 用于进行翻译。此函数使用使用 maketrans() 指定的转换映射。
Syntax : translate(table, delstr)
Parameters :
table : Translate mapping specified to perform translations.
delstr : The delete string can be specified as optional argument is not mentioned in table.
Returns : Returns the argument string after performing the translations using the translation table.
代码 #1:使用 translate() 和 maketrans() 进行翻译的代码。
# Python3 code to demonstrate
# translations using
# maketrans() and translate()
# specify to translate chars
str1 = "wy"
# specify to replace with
str2 = "gf"
# delete chars
str3 = "u"
# target string
trg = "weeksyourweeks"
# using maketrans() to
# construct translate
# table
table = trg.maketrans(str1, str2, str3)
# 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
翻译也可以通过指定翻译字典并作为映射的对象传递来实现。在这种情况下,不需要 maketrans() 来执行翻译。
代码 #2:无需 maketrans() 即可翻译的代码。
# 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
应用 :
很多时候在编码或开发时可能会发生错误,这些功能提供了一种简单快捷的方法来替换和纠正它们,并且可能会节省大量时间。