在Python中實(shí)現(xiàn)替換字符串中的子串的示例
假如有個(gè)任務(wù): 給定一個(gè)字符串,通過(guò)查詢字典,來(lái)替換給定字符中的變量。如果使用通常的方法:
>>> "This is a %(var)s" % {"var":"dog"}
'This is a dog'
>>>
其實(shí)可以使用string.Template類來(lái)實(shí)現(xiàn)上面的替換
>>> from string import Template
>>> words = Template("This is $var")
>>> print(words.substitute({"var": "dog"})) # 通過(guò)字典的方式來(lái)傳參
This is dog
>>> print(words.substitute(var="dog")) # 通過(guò)關(guān)鍵字方式來(lái)傳參
This is dog
>>>
在創(chuàng)建Template實(shí)例時(shí),在字符串格式中,可以使用兩個(gè)美元符來(lái)代替$,還可以用${}將 變量擴(kuò)起來(lái),這樣的話,變量后面還可以接其他字符或數(shù)字,這個(gè)使用方式很像Shell或者Perl里面的語(yǔ)言。下面以letter模板來(lái)示例一下:
>>> from string import Template
>>> letter = """Dear $customer,
... I hope you are having a great time!
... If you do not find Room $room to your satisfaction, let us know.
... Please accept this $$5 coupon.
... Sincerely,
... $manager,
... ${name}Inn"""
>>> template = Template(letter)
>>> letter_dict = {"name": "Sleepy", "customer": "Fred Smith", "manager": "Tom Smith", "room": 308}
>>> print(template.substitute(letter_dict))
Dear Fred Smith,
I hope you are having a great time!
If you do not find Room 308 to your satisfaction, let us know.
Please accept this $5 coupon.
Sincerely,
Tom Smith,
SleepyInn
>>>
有時(shí)候,為了給substitute準(zhǔn)備一個(gè)字典做參數(shù),最簡(jiǎn)單的方法是設(shè)定一些本地變量,然后將這些變量交給local()(此函數(shù)創(chuàng)建一個(gè)字典,字典中的key就是本地變量,本地變量的值通過(guò)key來(lái)訪問(wèn))。
>>> locals() # 剛進(jìn)入時(shí),沒(méi)有其他變量
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> name = "Alice" # 創(chuàng)建本地變量name
>>> age = 18 # 創(chuàng)建本地變量age
>>> locals() # 再執(zhí)行l(wèi)ocals()函數(shù)就可以看到name, age的鍵值隊(duì)
{'name': 'Alice', '__builtins__': <module '__builtin__' (built-in)>, 'age': 18, '__package__': None, '__name__': '__mai
__', '__doc__': None}
>>> locals()["name"] # 通過(guò)鍵name來(lái)獲取值
'Alice'
>>> locals()["age"] # 通過(guò)鍵age來(lái)獲取值
18
>>>
有了上面的例子打底來(lái)看一個(gè)示例:
>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for number in range(10):
... square = number * number
... print msg.substitute(locals())
...
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
另外一種方法是使用關(guān)鍵字參數(shù)語(yǔ)法而非字典,直接將值傳遞給substitute。
>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for i in range(4):
... print msg.substitute(number=i, square=i*i)
...
The square of 0 is 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
>>>
甚至可以同時(shí)傳遞字典和關(guān)鍵字
>>> from string import Template
>>> msg = Template("The square of $number is $square")
>>> for number in range(4):
... 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
>>>
為了防止字典的條目和關(guān)鍵字參數(shù)顯示傳遞的值發(fā)生沖突,關(guān)鍵字參數(shù)優(yōu)先,比如:
>>> from string import Template
>>> msg = Template("It is $adj $msg")
>>> adj = "interesting"
>>> print(msg.substitute(locals(), msg="message"))
It is interesting message
以上這篇在Python中實(shí)現(xiàn)替換字符串中的子串的示例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- python替換字符串中的子串圖文步驟
- python實(shí)現(xiàn)求兩個(gè)字符串的最長(zhǎng)公共子串方法
- Python實(shí)現(xiàn)統(tǒng)計(jì)給定字符串中重復(fù)模式最高子串功能示例
- Python實(shí)現(xiàn)針對(duì)給定字符串尋找最長(zhǎng)非重復(fù)子串的方法
- Python簡(jiǎn)單實(shí)現(xiàn)查找一個(gè)字符串中最長(zhǎng)不重復(fù)子串的方法
- Python實(shí)現(xiàn)判斷一個(gè)字符串是否包含子串的方法總結(jié)
- Python字符串中查找子串小技巧
- python七種方法判斷字符串是否包含子串
相關(guān)文章
Python數(shù)據(jù)結(jié)構(gòu)之棧、隊(duì)列的實(shí)現(xiàn)代碼分享
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)之棧、隊(duì)列的實(shí)現(xiàn)代碼分享,具有一定參考價(jià)值,需要的朋友可以了解下。2017-12-12
python神經(jīng)網(wǎng)絡(luò)學(xué)習(xí)利用PyTorch進(jìn)行回歸運(yùn)算
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)學(xué)習(xí)利用PyTorch進(jìn)行回歸運(yùn)算的實(shí)現(xiàn)代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Python實(shí)現(xiàn)ATM系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)ATM系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02
使用python進(jìn)行廣告點(diǎn)擊率的預(yù)測(cè)的實(shí)現(xiàn)
這篇文章主要介紹了使用python進(jìn)行廣告點(diǎn)擊率的預(yù)測(cè)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
Python?tracemalloc跟蹤內(nèi)存分配問(wèn)題
這篇文章主要介紹了Python?tracemalloc跟蹤內(nèi)存分配問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11

