11


一次完成多個替換:
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

 



 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章