我是靠谱客的博主 结实发夹,最近开发中收集的这篇文章主要介绍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字符串替换实例分析的全部内容,希望文章能够帮你解决Python字符串替换实例分析所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(126)

评论列表共有 0 条评论

立即
投稿
返回
顶部