Python中的字符串替换操作示例

yipeiwu_com5年前Python基础

字符串的替换(interpolation), 可以使用string.Template, 也可以使用标准字符串的拼接.
string.Template标示替换的字符, 使用"$"符号, 或 在字符串内, 使用"${}"; 调用时使用string.substitute(dict)函数.
标准字符串拼接, 使用"%()s"的符号, 调用时, 使用string%dict方法.
两者都可以进行字符的替换.

代码:

# -*- coding: utf-8 -*- 
 
import string 
 
values = {'var' : 'foo'} 
 
tem = string.Template(''''' 
Variable : $var 
Escape : $$ 
Variable in text : ${var}iable 
''') 
 
print 'TEMPLATE:', tem.substitute(values) 
 
str = ''''' 
Variable : %(var)s 
Escape : %% 
Variable in text : %(var)siable 
''' 
 
print 'INTERPOLATION:', str%values 

输出:

TEMPLATE:  
Variable : foo 
Escape : $ 
Variable in text : fooiable 
 
INTERPOLATION:  
Variable : foo 
Escape : % 
Variable in text : fooiable 

连续替换(replace)的正则表达式(re)
字符串连续替换, 可以连续使用replace, 也可以使用正则表达式.
正则表达式, 通过字典的样式, key为待替换, value为替换成, 进行一次替换即可.

代码

# -*- coding: utf-8 -*-

import re

my_str = "(condition1) and --condition2--"
print my_str.replace("condition1", "").replace("condition2", "text")

rep = {"condition1": "", "condition2": "text"}
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
my_str = pattern.sub(lambda m: rep[re.escape(m.group(0))], my_str)

print my_str

输出:

() and --text--
() and --text--

相关文章

python分块读取大数据,避免内存不足的方法

如下所示: def read_data(file_name): ''' file_name:文件地址 ''' inputfile = open(file_name, 'rb'...

python 装饰器功能以及函数参数使用介绍

python 装饰器功能以及函数参数使用介绍

简单的说:装饰器主要作用就是对函数进行一些修饰,它的出现是在引入类方法和静态方法的时候为了定义静态方法出现的。例如为了把foo()函数声明成一个静态函数 复制代码 代码如下: class...

Python列表切片用法示例

本文实例讲述了Python列表切片用法。分享给大家供大家参考,具体如下: Python中符合序列的有序序列都支持切片(slice),例如列表,字符串,元组。   &n...

Python tkinter模块弹出窗口及传值回到主窗口操作详解

Python tkinter模块弹出窗口及传值回到主窗口操作详解

本文实例讲述了Python tkinter模块弹出窗口及传值回到主窗口操作。分享给大家供大家参考,具体如下: 有些时候,我们需要使用弹出窗口,对程序的运行参数进行设置。有两种选择 一、标...

python判断字符串编码的简单实现方法(使用chardet)

本文实例讲述了python判断字符串编码的方法。分享给大家供大家参考,具体如下: 安装chardet模块 chardet文件夹放在/usr/lib/python2.4/site-pack...