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

相关文章

python自动化测试之从命令行运行测试用例with verbosity

python自动化测试之从命令行运行测试用例with verbosity

本文实例讲述了python自动化测试之从命令行运行测试用例with verbosity,分享给大家供大家参考。具体如下: 实例文件recipe3.py如下: class RomanN...

windows环境下tensorflow安装过程详解

windows环境下tensorflow安装过程详解

一、前言 本次安装tensorflow是基于Python的,安装Python的过程不做说明(既然决定按,Python肯定要先了解啊):本次教程是windows下Anaconda安装Ten...

Pandas读取MySQL数据到DataFrame的方法

方法一: #-*- coding:utf-8 -*- from sqlalchemy import create_engine class mysql_engine(): us...

对Pyhon实现静态变量全局变量的方法详解

python不能像C++一样直接定义一个static变量或者通过extern来导入别的库的变量而实现数据共享,但是python的思想是通过模块化来解决这个问题,就是通过模块来实现全局变量...

python实现简单成绩录入系统

学了一个多月的python,做了一个小程序:python实现简单成绩录入系统,实验一下 menu部分 from tkinter import*#这是一个python模块,python...