如何用新字符串替换 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?
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
使用模式对象替换 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?
广告