手机
当前位置:查字典教程网 >脚本专栏 >python >Python字符串替换实例分析
Python字符串替换实例分析
摘要:本文实例讲述了Python字符串替换的方法。分享给大家供大家参考。具体如下:单个字符替换s='abcd'a=["a","b","c"]b=[...

本文实例讲述了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 学习笔记

Python getopt模块处理命令行选项实例

Python 过滤字符串的技巧,map与itertools.imap

Python写的一个简单DNS服务器实例

Python ORM框架SQLAlchemy学习笔记之数据查询实例

Python 获取新浪微博的最新公共微博实例分享

Python时间戳与时间字符串互相转换实例代码

Python 字符串中的字符倒转

python列表与元组详解实例

python字符串替换示例

精品推荐
分类导航