Python函数replace()用法,替换字符串中的子字符串。
replace()函数是Python内置的字符串函数,用于将一个字符串中的子字符串替换为指定的字符串。
语法格式:
str.replace(old, new[, count])
参数说明:
old:需要被替换的子字符串。
new:需要替换成的新字符串。
count:可选参数,替换次数,如果指定了此参数,则最多替换次数为count次。如果不指定,则默认替换所有匹配的子字符串。
下面我们来看一些具体的例子:
1. 替换字符串中的子字符串
s = "hello world"
s_new = s.replace("hello", "hi")
print(s_new)
输出结果为:“hi world”。
这个例子中,我们将字符串s中的子字符串“hello”替换为了“hi”。
2. 替换指定次数
s = "hello world hello world"
s_new = s.replace("hello", "hi", 1)
print(s_new)
输出结果为:“hi world hello world”。
在这个例子中,我们将字符串s中的 次出现的“hello”替换为了“hi”,因为指定了替换次数为1。
3. 替换多个子字符串
s = "apple banana cherry"
s_new = s.replace("apple", "orange").replace("banana", "peach").replace("cherry", "grape")
print(s_new)
输出结果为:“orange peach grape”。
这个例子中,我们依次将字符串s中的“apple”替换为“orange”,“banana”替换为“peach”,“cherry”替换为“grape”。
4. 替换包含特殊字符的子字符串
s = "Hi there! How's the weather today?"
s_new = s.replace("Hi", "Hello").replace("!", "?").replace("'", "’")
print(s_new)
输出结果为:“Hello there? How’s the weather today?”
这个例子中,我们将字符串s中的“Hi”替换为“Hello”,将“!”替换为“?”,将“'”替换为“’”。
总结:
Python函数replace()用于替换字符串中的子字符串,其用法非常灵活。在实际的编程中,我们可以使用replace()函数实现非常多的字符串操作,比如替换指定字符、过滤敏感字符、删除空格等。因此,我们需要熟练掌握replace()函数的用法,以便更好地完成字符串处理的任务。
