Python字符串替换实例分析

yipeiwu_com5年前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程序设计有所帮助。

相关文章

用Pycharm实现鼠标滚轮控制字体大小的方法

用Pycharm实现鼠标滚轮控制字体大小的方法

一、pycharm字体放大的设置 File —> setting —> Keymap —>在搜寻框中输入:increase —> Increase Font Si...

Python2和Python3中urllib库中urlencode的使用注意事项

前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urle...

wxpython 学习笔记 第一天

1,导入 wxpython 库 import wx 2,建立窗体构造类 class 名字(wx.Frame): def __init__(self, parent, id): wx.Fr...

Python迭代用法实例教程

本文实例讲述了Python中迭代的用法,是一个非常实用的技巧。分享给大家供大家参考借鉴之用。具体分析如下: 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或t...

Windows下python2.7.8安装图文教程

Windows下python2.7.8安装图文教程

本文为大家分享了python2.7.8安装图文教程,供大家参考,具体内容如下 1、进入python的官方网站下载:https://www.python.org/,点击Download,选...