Python String maketrans() 函數用於構造轉換表,即指定整個字符串中需要替換的字符列表或需要從字符串中刪除的字符。
用法:
maketrans(str1,str2,str3)
參數:
- str1:指定需要替換的字符列表。
- str2:指定需要替換字符的字符列表。
- str3:指定需要刪除的字符列表。
返回值:
返回指定 translate() 可以使用的轉換的轉換表
使用 maketrans() 進行翻譯
翻譯字符串中的字符 translate() 用於進行翻譯。此函數使用使用 maketrans() 指定的轉換映射。
用法:
翻譯(表,delstr)
參數:
- 表:指定翻譯映射以執行翻譯。
- 德爾斯特:刪除字符串可以指定為表中未提及的可選參數。
返回值:使用翻譯表執行翻譯後返回參數字符串。
示例:使用 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
相關用法
- Python maketrans() and translate()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isspace()用法及代碼示例
- Python String index()用法及代碼示例
注:本文由純淨天空篩選整理自AmiyaRanjanRout大神的英文原創作品 Python String maketrans() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。