当前位置: 移动技术网 > IT编程>脚本编程>Python > Python字符串替换实例分析

Python字符串替换实例分析

2018年06月18日  | 移动技术网IT编程  | 我要评论

89890漫画,厦门到大金湖,三亚天气预报15天

本文实例讲述了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程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网