国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

在Python中實現(xiàn)替換字符串中的子串的示例

2020-01-04 14:10:52
字體:
供稿:網(wǎng)友

假如有個任務(wù): 給定一個字符串,通過查詢字典,來替換給定字符中的變量。如果使用通常的方法:

>>> "This is a %(var)s" % {"var":"dog"}'This is a dog'>>>

其實可以使用string.Template類來實現(xiàn)上面的替換

>>> from string import Template>>> words = Template("This is $var")>>> print(words.substitute({"var": "dog"})) # 通過字典的方式來傳參This is dog>>> print(words.substitute(var="dog"))   # 通過關(guān)鍵字方式來傳參This is dog>>>

在創(chuàng)建Template實例時,在字符串格式中,可以使用兩個美元符來代替$,還可以用${}將 變量擴起來,這樣的話,變量后面還可以接其他字符或數(shù)字,這個使用方式很像Shell或者Perl里面的語言。下面以letter模板來示例一下:

>>> 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>>>

有時候,為了給substitute準(zhǔn)備一個字典做參數(shù),最簡單的方法是設(shè)定一些本地變量,然后將這些變量交給local()(此函數(shù)創(chuàng)建一個字典,字典中的key就是本地變量,本地變量的值通過key來訪問)。

>>> locals()   # 剛進入時,沒有其他變量{'__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的鍵值隊{'name': 'Alice', '__builtins__': <module '__builtin__' (built-in)>, 'age': 18, '__package__': None, '__name__': '__mai__', '__doc__': None}>>> locals()["name"] # 通過鍵name來獲取值'Alice'>>> locals()["age"] # 通過鍵age來獲取值18>>>

有了上面的例子打底來看一個示例:

>>> 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 0The square of 1 is 1The square of 2 is 4The square of 3 is 9

另外一種方法是使用關(guān)鍵字參數(shù)語法而非字典,直接將值傳遞給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 0The square of 1 is 1The square of 2 is 4The square of 3 is 9>>>

甚至可以同時傳遞字典和關(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 0The square of 1 is 1The square of 2 is 4The 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中實現(xiàn)替換字符串中的子串的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到python教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 时尚| 梧州市| 惠东县| 乐都县| 德钦县| 焦作市| 忻州市| 凤山县| 墨玉县| 抚宁县| 阿拉善右旗| 三台县| 永和县| 广平县| 阜康市| 额敏县| 阳新县| 封开县| 全南县| 陇南市| 慈利县| 顺平县| 德清县| 比如县| 西乌珠穆沁旗| 沽源县| 梅河口市| 高碑店市| 阜南县| 鹿邑县| 察雅县| 镇宁| 卓尼县| 盈江县| 彭泽县| 奈曼旗| 武邑县| 开封市| 彩票| 漯河市| 中宁县|