手机
当前位置:查字典教程网 >脚本专栏 >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实现类继承实例

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

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

Python学习笔记_数据排序方法

Python学习资料

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

Python 字符串操作实现代码(截取/替换/查找/分割)

python实现文件名批量替换和内容替换

从零学python系列之数据处理编程实例(一)

python列表与元组详解实例

精品推荐
分类导航