sub函数替换字符串中的子串?
发布时间:2023-12-09 14:07:34
sub函数在字符串方法中用于替换字符串中的子串。
语法:
string.sub(old, new[, count])
参数:
- old: 要被替换的子串。
- new: 替换后的新子串。
- count: 可选参数,指定替换的次数。
返回值:
返回替换后的新字符串。
示例:
string = "Hello World"
new_string = string.sub("World", "Python")
print(new_string) # 输出:Hello Python
string = "Hello Hello Hello"
new_string = string.sub("Hello", "Python", 2)
print(new_string) # 输出:Python Python Hello
上述示例中,sub函数将字符串string中的旧子串"World"替换为新子串"Python",并将替换后的新字符串赋值给new_string变量。其输出为"Hello Python"。
在第二个示例中,sub函数将字符串string中的旧子串"Hello"替换为新子串"Python",但是它只会替换前两个匹配的子串。因此,替换后的新字符串输出为"Python Python Hello"。
