1. 程式人生 > >Python中實現替換字串中的子串

Python中實現替換字串中的子串

假如有個任務: 給定一個字串,通過查詢字典,來替換給定字元中的變數。如果使用通常的方法:

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

其實可以使用string.Template類來實現上面的替換

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

在建立Template例項時,在字串格式中,可以使用兩個美元符來代替$,還可以用${}將 變數擴起來,這樣的話,變數後面還可以接其他字元或數字,這個使用方式很像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準備一個字典做引數,最簡單的方法是設定一些本地變數,然後將這些變數交給local()(此函式建立一個字典,字典中的key就是本地變數,本地變數的值通過key來訪問)。

>>> locals()         # 剛進入時,沒有其他變數
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> name = "Alice"   # 建立本地變數name 
>>> age = 18         # 建立本地變數age
>>> locals()         # 再執行locals()函式就可以看到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 0
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9

另外一種方法是使用關鍵字引數語法而非字典,直接將值傳遞給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
>>>

 甚至可以同時傳遞字典和關鍵字

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

為了防止字典的條目和關鍵字引數顯示傳遞的值發生衝突,關鍵字引數優先,比如:

>>> from string import Template
>>> msg = Template("It is $adj $msg")
>>> adj = "interesting"
>>> print(msg.substitute(locals(), msg="message"))
It is interesting message

相關推薦

Python實現替換字串的子

假如有個任務: 給定一個字串,通過查詢字典,來替換給定字元中的變數。如果使用通常的方法: >>> "This is a %(var)s" % {"var":"dog"} 'This is a dog' >>> 其實可以使用string.

字串中子出現的次數(c++實現

題目如題目所示。 程式碼如下:int findSubStringNUM(const char* targetString,const char* subString){ assert(NULL!=targetString||NULL!=subString); int i

oracle實現擷取字串(substr)、查詢字串位置(instr)、替換字串(replace)

 (1)oracle中實現擷取字串:substr substr(string, start_position, [length]) 其中,string是元字串,start_position為開始位

python實現字符使用非"+"號拼接的方式實現

逗號 adf ado rom 使用 vpd 脈脈 data ges 在脈脈上看到一片在程序中對字符串拼接的實現,不用+號如何完成字符串拼接,大概看了下評論,大部分都是說在java中實現不使用+號,完成字符串的拼接操作,在此之前我也是安裝以往經驗for循環遍歷列表使用+號完成

Python如何將字符作為變量名

名字空間 檢測 lis port eval() div 有效 else 安全性 應用場景描述: 通過配置文件獲取服務器上配置的服務名及運行端口號,編寫python腳本檢測服務上服務是否在運行? #!/usr/bin/env python # -*- codi

Python編碼和字符

bytes 單引號 byte 引號 com for log 統一處理 解碼 編碼和字符串 編碼 在學習回顧中總結一下ASCII編碼、Unicode編碼和utf-8編碼。 計算機中只能處理數字,我們若要處理文本的話就要將文件轉換為數字。所以,這就涉及該怎樣轉換的問題,也就是編

python實現對文件的寫入,讀取,復制,批量重命名

python 文件操作 1.寫入內容至文件中 def write_file(): open_file = open("xxxx.txt","w") open_file.write("i want to open a file and write this.\n") open_f

案例:python實現51備忘錄

python1.添加Memo類,至少包含id,name,thing,date四個屬性,date可以暫時使用字符串表示,比如‘1.2’,‘3.8’,暫時不用考慮時間相關模塊 2.id屬性為只讀,其他屬性可讀寫 3.添加MemoAdmin類,作為主體程序,管理Memo類構成的列表,進行Memo的增刪改查(相應方法

PythonList和字符類型的相互轉換

相互轉換 join world 字符串類型 類型 引號 style spa 字符串類 1.字符串轉換成List a = ‘Hello World!‘ a_list = list(a) //[‘H‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘W‘, ‘o‘, ‘

python實現線性回歸(linear regression)

lsa d+ 分享圖片 通過 nsq mps mile edi mfp 1 什麽是線性回歸 確定因變量與多個自變量之間的關系,將其擬合成線性關系構建模型,進而預測因變量 2 線性回歸原理 最小二乘法OLS(ordinary learst squares) 模型的y與實際值y

Python替換函式---replace(),re.sub()和strip()

這是原文,寫的很好,共勉! 1. replace() 物件.replace(rgExp, replaceText, max) rgExp,replaceText是必須要有的,max是可選的引數,可以不加 在物件的每個rgExp都替換成replaceText,從左到右最多max

Python 找出字串出現頻率最高的字母

發現一個學Python的好網站 https://py.checkio.org 第一題大概意思就是找出一個字串中出現頻率最高字母 我的思路也是直接,弄個字典,遍歷字串,將鍵值對填進字典裡,健就是字母,值就是出現了幾次,再查下字典裡最大的值即可。 上我的程式碼 import

Python常用操作字串的函式與方法總結

本文轉載自:https://www.jb51.net/article/79196.htm Python中常用操作字串的函式與方法總結 這篇文章主要介紹了Python中常用操作字串的函式與方法總結,包括字串的格式化輸出與拼接等基礎知識,需要的朋友可以參考下 例如這樣一個字串 Python,

如何在python實現整數的二進位制迴圈移位(附程式碼)

【時間】2018.11.03 【題目】如何在python中實現整數的二進位制迴圈移位(附程式碼) 概述 在python中,可以通過<<以及>>運算子實現二進位制的左移位以及右移位,然而並沒有實現迴圈移位的運算子,暫時也找不到可以實現迴圈移位的函式,所以在本文中,主

如何在Python實現這五類強大的概率分佈

如何在Python中實現這五類強大的概率分佈 中文譯文原連結,侵刪。 英文出處|How to implement these 5 powerful probability distributions in Python R程式語言已經成為統計分析中的事實標準。但在這篇文

python,獲取字串的長度

說明:   與其他的語言一樣,有時候需要檢視或者說計算字串的長度。在此記錄下python中通過哪個函式實現。 操作過程: 1.通過len()函式返回字串的長度 >>> text='python' >>> len(text) 6 >>>

演算法篇:計算字串中子的出現次數(java)

演算法篇:計算字串中子串的出現次數(java) 方法一:使用String類的substring(indexStart,indexEnd)方法 首先解釋一下substring(indexStart,indexEnd)方法: str.substring(indexStart,inde

Python必備的字串拼接方法,你知道多少?

python拼接字串一般有以下幾種方法: ①直接通過(+)操作符拼接 s = 'Hello'+' '+'World'+'!' print(s) 輸出結果:Hello World! 使用這種方式進行字串連線的操作效率低下,因為python中使用 + 拼接兩個字串時會生成

python位元組與字串的轉換

#bytes object     byte = b"byte example"     # str object     str = "str example"   &nbs

python實現單例模式

單例模式(Singleton Pattern)是一種常用的軟體設計模式,該模式的主要目的是確保某一個類只有一個例項存在。當你希望在整個系統中,某個類只能出現一個例項時,單例物件就能派上用場。 比如,某個伺服器程式的配置資訊存放在一個檔案中,客戶端通過一個 AppConfig