python字符串替换

#单个字符替换

s = 'abcd'
a = ["a", "b", "c"]
b = ["c", "d", "e"]

import string
s.translate(string.maketrans(''.join(a),''.join(b)))
print s

#字符串,改善版

s = "hello, i'm mouren, hehe~~,hehe~~mourenmouren"
a = ["mouren", "hehe"]
b = ["mr", "hoho"]
import re
dic = dict(zip(a,b))
pattern = re.compile('(' + '|'.join(a) + ')')
s = pattern.sub(lambda a:dic[a.group()], s)
print s

原文地址:https://www.cnblogs.com/imouren/p/2092268.html