Python字符串替换实例分析
2015-05-11 00:00
627 查看
本文实例讲述了Python字符串替换的方法。分享给大家供大家参考。具体如下:
单个字符替换
输出结果为:abcd
字符串替换,改善版
输出结果为:hello, i'm mr, hoho~~,hoho~~mrmr
希望本文所述对大家的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正则表达式使用实例-替换字符串HTML标签
- Python正则表达式如何进行字符串替换实例
- Python 字符串(三)-字符串操作实例(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python字符串拼接、截取及替换方法总结分析
- Python字符串拼接、截取及替换方法总结分析
- c#实例化继承类,必须对被继承类的程序集做引用 .net core Redis分布式缓存客户端实现逻辑分析及示例demo 数据库笔记之索引和事务 centos 7下安装python 3.6笔记 你大波哥~ C#开源框架(转载) JSON C# Class Generator ---由json字符串生成C#实体类的工具
- Python原始字符串与Unicode字符串操作符用法实例分析
- Python正则表达式如何进行字符串替换
- Python字符串操作之字符串搜索与替换
- Python中使用MELIAE分析程序内存占用实例
- Python:字符串的多重替换
- Python基类函数的重载与调用实例分析
- Python字符串的方法,查找和替换
- 一个python替换字符串的函数
- Python爬虫DNS解析缓存方法实例分析
- python中enumerate函数用法实例分析
- python实现数值积分的Simpson方法实例分析
- Python 列表替换字符串的数据
- python列表操作之extend和append的区别实例分析