本文實例講述了Python字符串替換的方法。分享給大家供大家參考。具體如下:
單個字符替換
s = 'abcd'a = ["a", "b", "c"]b = ["c", "d", "e"]import strings.translate(string.maketrans(''.join(a),''.join(b)))print s
輸出結果為:abcd
字符串替換,改善版
s = "hello, i'm mouren, hehe~~,hehe~~mourenmouren"a = ["mouren", "hehe"]b = ["mr", "hoho"]import redic = dict(zip(a,b))pattern = re.compile('(' + '|'.join(a) + ')')s = pattern.sub(lambda a:dic[a.group()], s)print s
輸出結果為:hello, i'm mr, hoho~~,hoho~~mrmr
希望本文所述對大家的Python程序設計有所幫助。
新聞熱點
疑難解答