Python 字符串 translate() 方法

Python translate() 语法

translate() 是 Python 字符串的一个方法,它使用一个映射表(也叫 “翻译表” 或 “转换表”)来替换或删除字符串中的某些字符。

其中,翻译表是一个字典,或者是由 maketrans() 方法创建的表。

语法:

str.translate(table)

说明:

translate() 方法接收单个参数。

  • table(必选):是一个字典,或由 maketrans() 方法创建的表。如果 table 中包含的字符不在原字符串中,则这些字符不会被处理。

注意:

  • translate() 的转换是基于单个字符的,它不支持子字符串的替换。如果需要替换子字符串,我们应该使用 replace() 方法。
  • translate() 比多次调用 replace() 来替换单个字符的效率更高,因为它只需要一次遍历字符串。

Python translate() 摘要

使用频率
修改原字符串
官方文档 查看
相关方法 replace()maketrans()

Python translate() 示例

接下来,我们通过几个简单的例子来讲解 Python translate() 方法是如何使用的。

示例 1:translate() 参数是一个字典

table = {97: '*', 98: '$', 99: '@'}
s = 'apple,banana,cat'
result = s.translate(table)
print(result)

运行结果如下。

*pple,$*n*n*,@*t

分析:

当 translate() 的参数是一个字典时,它要求字典的键是 Unicode 值。从 Unicode 表可以知道,97 对应 'a',98 对应 'b',99 对应 'c'。

s.translate(table) 表示会将 s 中的 'a' 替换成 '*',将 'b' 替换成 '$',并将 'c' 替换成 '@'。

示例 2:translate() 删除字符

table = {97: None, 98: None, 99: None}
s = 'apple,banana,cat'
result = s.translate(table)
print(result)

运行结果如下。

pple,nn,t

分析:

当字典的值为 None 时,表示将对应的字符替换成 None,也就是删除该字符。

示例 3:结合 maketrans() 创建的映射表

# 创建映射表
s1 = 'abc'
s2 = 'hij'
table = str.maketrans(s1, s2)

# 实现替换
s = 'apple,banana,cat'
result = s.translate(table)
print(result)

运行结果如下。

hpple,ihnhnh,jht

分析:

在这个例子中,str.maketrans() 会在底层自动为我们创建一个基于 Unicode 编码的映射表:{97: 104, 98: 105, 99: 106}。这免去了我们手动去查找字符对应的 Unicode 值的麻烦。

如果小伙伴们不了解 maketrans() 都干了些什么,请先查看:Python maketrans() 方法

translate() 与 replace() 对比

translate() 和 replace() 这 2 个方法都可以实现替换字符串的功能,它们之间的区别如下:

  • translate():适合批量替换或删除,效率更高。
  • replace():适合简单替换(如单字符或固定子串)。

示例 4:translate() vs replace()

s = 'abcdef'

# 使用 translate()
table = str.maketrans('abc', 'xyz')
result1 = s.translate(table)
print(result1)

# 使用 replace()
result2 = s.replace('a', 'x').replace('b', 'y').replace('c', 'z')
print(result2)

运行结果如下。

xyzdef
xyzdef

分析:

相比于 replace(),translate() 在多次替换时不会创建中间字符串,这样性能更高。

上一篇: maketrans()

下一篇: ljust()

给站长反馈

绿叶网正在不断完善中,小伙伴们如果发现任何问题,还望多多给站长反馈,谢谢!

邮箱:lvyenet@vip.qq.com

「绿叶网」服务号
绿叶网服务号放大
关注服务号,微信也能看教程。
绿叶网服务号