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”。
首先,在Python中安装re模块以使用正则表达式-
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?