Python字符串替换实例分析

yipeiwu_com6年前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 保存float类型的小数的位数方法

python保留两位小数: In [1]: a = 5.026 In [2]: b = 5.000 In [3]: round(a,2) Out[3]: 5.03 In [4]...

Python过滤txt文件内重复内容的方法

Python过滤txt文件内重复内容的方法

Python过滤txt文件内重复内容,并将过滤后的内容保存到新的txt中 示例如下 原文件 处理之后的文件 直接上代码 # -*-coding:utf-8 -*- f = o...

Python的函数的一些高阶特性

高阶函数英文叫Higher-order function。什么是高阶函数?我们以实际代码为例子,一步一步深入概念。 变量可以指向函数 以Python内置的求绝对值的函数abs()为例,调...

Numpy 中的矩阵求逆实例

1. 矩阵求逆 import numpy as np a = np.array([[1, 2], [3, 4]]) # 初始化一个非奇异矩阵(数组) print(np.linalg...

Python 私有函数的实例详解

Python 私有函数的实例详解 与大多数语言一样,Python 也有私有的概念: • 私有函数不可以从它们的模块外面被调用 • 私有类方法不能够从它们的类外面...