Python字符串替換實例分析
更新時間:2015年05月11日 10:24:06 作者:蛇小狼
這篇文章主要介紹了Python字符串替換的方法,實例對比分析了單個字符替換與字符串替換的相關技巧,非常簡單實用,需要的朋友可以參考下
本文實例講述了Python字符串替換的方法。分享給大家供大家參考。具體如下:
單個字符替換
s = 'abcd' a = ["a", "b", "c"] b = ["c", "d", "e"] import string s.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 re dic = 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程序設計有所幫助。
您可能感興趣的文章:
相關文章
Python人工智能之路 jieba gensim 最好別分家之最簡單的相似度實現(xiàn)
這篇文章主要介紹了Python人工智能之路 jieba gensim 最好別分家之最簡單的相似度實現(xiàn) ,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-08-08