Python中的maketrans()和translate()函数

在编程领域,几乎不需要一次替换整个文件中的所有单词/字符。python使用函数translate()及其辅助函数maketrans()提供此功能。本文将讨论这两种功能。

null
maketrans()

maketrans()函数用于构造转换表,即指定整个字符串中需要替换的字符列表或需要从字符串中删除的字符列表

语法: maketrans(str1、str2、str3)

参数: str1: 指定需要替换的字符列表。 str2: 指定需要替换字符的字符列表。 str3: 指定需要删除的字符列表。

返回: 返回指定translate()可以使用的转换的转换表

使用maketrans()进行翻译

翻译字符串中的字符translate()用于进行翻译。此函数使用使用maketrans()指定的转换映射。

语法: 翻译(表格,delstr)

参数: 表: 指定用于执行转换的转换映射。 德尔斯特: 删除字符串可以指定为表中未提及的可选参数。

返回: 使用翻译表执行翻译后返回参数字符串。

代码#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进行翻译()

翻译也可以通过指定翻译字典和作为映射的对象传递来实现。在这种情况下,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

申请: 在编码或开发过程中,有很多时候可能会出现错误,这些函数提供了一种简单快速的方法来替换和纠正错误,并可能节省大量时间。

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享