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

yipeiwu_com6年前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的列表中利用remove()方法删除元素的教程

 remove()方法从列表中删除第一个obj。 语法 以下是remove()方法的语法: list.remove(obj) 参数   &n...

python用ConfigObj读写配置文件的实现代码

发现一个简单而又强大的读写配置文件的lib,http://www.voidspace.org.uk/python/configobj.html。个人觉得最大的亮点在于自带的格式校验功能,...

python实现数独游戏 java简单实现数独游戏

python实现数独游戏 java简单实现数独游戏

 使用python和java实现数独游戏,有比较才有收获哦。 1、Python版 #--coding:utf-8-- import random import itert...

Python 限制线程的最大数量的方法(Semaphore)

如下所示: import threading import time sem=threading.Semaphore(4) #限制线程的最大数量为4个 def gothrea...

解决python中os.listdir()函数读取文件夹下文件的乱序和排序问题

解决python中os.listdir()函数读取文件夹下文件的乱序和排序问题

1. os.listdir()概述 os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。 例如: dir ='F:/Home_01/img'#当前目录...