2019-02-23
閱讀量:
734
Python查詢和替換一個(gè)文本字符串的方法
答:可以使用re模塊中的sub()函數(shù)或者subn()函數(shù)來進(jìn)行查詢和替換,
格式:sub(replacement, string[,count=0])(replacement是被替換成的文本,string是需要被替換的文本,count是一個(gè)可選參數(shù),指最大被替換的數(shù)量)
>>> import re
>>>p=re.compile(‘blue|white|red’)
>>>print(p.sub(‘colour’,'blue socks and red shoes’))
colour socks and colourshoes
>>>print(p.sub(‘colour’,'blue socks and red shoes’,count=1))
colour socks and redshoes
subn()方法執(zhí)行的效果跟sub()一樣,不過它會(huì)返回一個(gè)二維數(shù)組,包括替換后的新的字符串和總共替換的數(shù)量






評(píng)論(0)


暫無數(shù)據(jù)
CDA考試動(dòng)態(tài)
CDA報(bào)考指南
推薦帖子
0條評(píng)論
0條評(píng)論
0條評(píng)論
0條評(píng)論