1. 程式人生 > >[python]字串替換format和re.sub

[python]字串替換format和re.sub

python字串的格式化函式format功能很強大,可以使用一個字典來替代多個格式化字串,可以用來實現類似模板的功能。

(replace只能替換單個字串,不適用)

s2="discriminator {vrf} local {_bfdlocal} remote {_bfdremote}"  
para={'vrf':'xinxi','bfdlocal':'100','bfdremote':'200'}
print(s3.format(**para))   #*代表引數為元組, **代表引數為字典

不過,由於format使用的格式化串只能用{}.更靈活的情況可以使用正則

re.sub的repl可以使用函式,可以實現原地加工+替換

s2="discriminator {vrf} local {_bfdlocal} remote {_bfdremote}"  
para={'vrf':'xinxi','A_m_bfdlocal':'100','A_m_bfdremote':'200'}
def fillpara(matched):
    name=matched.group('para')
    if name[0:1]=='_':
        return para[prefix+name]   #可以對替換引數進行加工
    else:
        return para[name]
        
p=re.compile('{(?P<para>.+?)}')
s4=re.sub(p, fillpara, s2)  #?代表非貪婪模式