python字符串替换

Posted on 2011-06-28 14:51  蛇小狼  阅读(268)  评论(0编辑  收藏  举报

#单个字符替换

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