Python 字符串 translate() 方法
示例
将所有 "S" 字符替换为 "P" 字符
# 使用字典,通过 ASCII 码将 83 (S) 替换为 80 (P)
mydict = {83: 80}
txt = "Hello Sam!"
print(txt.translate(mydict))
自己动手试一试 »
定义和用法
translate() 方法返回一个字符串,其中一些指定的字符被字典或映射表中描述的字符替换。
使用 maketrans() 方法创建映射表。
如果一个字符没有在字典/表中指定,它将不会被替换。
如果你使用字典,你必须使用 ASCII 码而不是字符。
语法
string.translate(table)
参数值
参数 | 描述 |
---|---|
table | 必需。可以是字典,或描述如何执行替换的映射表 |
更多示例
示例
使用映射表将 "S" 替换为 "P"
txt = "Hello Sam!"
mytable = str.maketrans("S", "P")
print(txt.translate(mytable))
自己动手试一试 »
示例
使用映射表替换多个字符
txt = "Hi Sam!"
x = "mSa"
y = "eJo"
mytable = str.maketrans(x, y)
print(txt.translate(mytable))
自己动手试一试 »
示例
映射表中的第三个参数描述了你想要从字符串中删除的字符
txt = "Good night Sam!"
x = "mSa"
y = "eJo"
z = "odnght"
mytable = str.maketrans(x, y, z)
print(txt.translate(mytable))
自己动手试一试 »
示例
与上面的例子相同,但使用字典而不是映射表
txt = "Good night Sam!"
mydict = {109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104: None, 116: None}
print(txt.translate(mydict))
自己动手试一试 »