手机
当前位置:查字典教程网 >脚本专栏 >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中字典(dict)和列表(list)的排序方法实例

python三元运算符实现方法

Python实现的简单万年历例子分享

Python的内存泄漏及gc模块的使用分析

python字符串替换示例

Python字符转换

python搭建简易服务器分析与实现

Python3基础之基本数据类型概述

Python 文件操作技巧(File operation) 实例代码分析

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

精品推荐
分类导航