如何用新字串替換 Python 子字串的所有出現?
在本文中,我們將實現各種示例來用新字串替換子字串的所有出現。假設我們有以下字串:
Hi, How are you? How have you been?
我們必須將所有“How ”子字串替換為“Demo”。因此,輸出應為 −
Hi, Demo are you? Demo have you been?
現在讓我們看一些示例 −
使用 replace() 方法替換 Python 子字串的所有出現
示例
在本例中,我們將使用 replace() 方法將 Python 子字串的所有出現替換為新字串:
# String myStr = "Hi, How are you? How have you been?" # Display the String print("String = " + myStr) # Replacing and returning a new string strRes = myStr.replace("How", "Demo") # Displaying the Result print("Result = " + strRes)
輸出
String = Hi, How are you? How have you been? Result = Hi, Demo are you? Demo have you been?
使用正則表示式 sub() 替換子字串的出現
假設您想替換不同的子字串。為此,我們可以使用正則表示式。在下面的示例中,我們將不同的子字串“What”和“How”替換為“Demo”。
首先,安裝 re 模組以在 Python 中使用正則表示式:
pip install re
然後,匯入 re 模組 −
import re
以下是完整的程式碼:
import re # String myStr = "Hi, How are you? What are you doing here?" # Display the String print("String = " + myStr) # Replacing and returning a new string strRes = re.sub(r'(How|What)', 'Demo', myStr) # Displaying the Result print("Result = " + strRes)
輸出
String = Hi, How are you? What are you doing here? Result = Hi, Demo are you? Demo are you doing here?
使用模式物件替換 Python 子字串的出現
示例
以下是程式碼 −
import re # String myStr1 = "Hi, How are you?" myStr2 = "What are you doing here?" # Display the String print("String1 = " + myStr1) print("String2 = " + myStr2) # Replacing with Pattern Objects pattern = re.compile(r'(How|What)') strRes1 = pattern.sub("Demo", myStr1) strRes2 = pattern.sub("Sample", myStr2) # Displaying the Result print("\nResult (string1) = " + strRes1) print("Result (string2) = " + strRes2)
輸出
String1 = Hi, How are you? String2 = What are you doing here? Result (string1) = Hi, Demo are you? Result (string2) = Sample are you doing here?
廣告