這篇文章主要介紹了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程序設計有所幫助。
新聞熱點
疑難解答