Python String maketrans() 方法
Python String 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 need to be deleted.
Returns:
Returns the translation table which specifies the conversions that can be used by translate()
使用 maketrans() 进行翻译
翻译字符中的字符串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.
示例:使用 translate() 和 maketrans() 进行翻译的代码
Python3
# 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