python批量替换字符的三种方法
import re
table = ''.maketrans('1234', 'abcd')
s2 = '1334r5254523343'
print(s2.translate(table))
dict1 = {"1": "a", "2": "b", "3": "c", "4": "d"}
rs = map(lambda x: dict1[x] if x in dict1.keys() else x, list(s2))
print("".join(list(rs)))
s = 'abcd'
str = "121114121111211dfge1112311"
str = re.sub(r'[1-4]', lambda x: s[int(x.group())-1], str)
print(str)
一translate 方法
先maketrans,把映射前后字符串写入
用 字符串.translate ( maketrans结果)
二map方法
先用list分解字符串,map 对应映射字典,把 字典的key,替换成为value , 把分解的字符串再用join连接
三、用re的替换方法
注意lambda的用法,lambda x:求X对应函数 ,要操作的原数据。