11

本文介绍了如何使用Python进行批量字符串替换的方法,并演示了通过正则表达式匹配和替换技术来高效处理字符串替换任务。此外,还展示了如何利用string模块中的Template类来简化带有变量的字符串模板处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一次完成多个替换:
import re
def multiple_replace(text,adict):
	rx=re.compile("|".join(map(re.escape,adict)))
	def one_xlat(match):
		return adict[match.group(0)]
	return rx.sub(one_xlat,text)
	
def make_xlat(*arge,**kwds):
	adict=dict(*arge,**kwds)
	rx=re.compile("|".join(map(re.escape,adict)))
	def one_xlat(match):
		return adict[match.group(0)]
	def xlat(text):
		return rx.sub(one_xlat,text)
	return xlat
if __name__=="__main__":
	text="larry wall is the creator of perl"
	adict={
	"larry wall":"guido van rossum",
	"creator":"brnevolent dictator for life",
	"perl":"python",
	}
	print multiple_replace(text,adict)
	translate=make_xlat(adict)
	print translate(text)
结果:
guido van rossum is the brnevolent dictator for life of python
guido van rossum is the brnevolent dictator for life of python
 


15页 检查字符串是否包含某字符集合的字符

for if 循环 itertools.ifilter defference containsALL symmetric_difference translate string.maketrans

 

import stringmsg=string.Template('the square of $number is $square')for number in range(10): square=number*number print msg.substitute(locals())for i in range(10): print msg.substitute(number=i,square=i*i)

for number in range(10): print msg.substitute(locals(),square=number*number)


 将所有变量传递到本地
the square of 0 is 0
the square of 1 is 1
the square of 2 is 4
the square of 3 is 9
the square of 4 is 16
the square of 5 is 25
the square of 6 is 36
the square of 7 is 49
the square of 8 is 64
the square of 9 is 81

 



 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值