📅  最后修改于: 2023-12-03 15:04:34.088000             🧑  作者: Mango
在Python中,我们可以使用replace()函数来替换一个字符串中的子字符串。replace()函数的语法如下:
str.replace(old, new[, count])
其中,old表示要被替换的旧字符串,new表示要替换成的新字符串,count表示替换的次数(可选参数,默认全部替换)。
举个例子:
str = "hello world"
new_str = str.replace("hello", "hi")
print(new_str)
输出结果为:hi world
在上面的例子中,我们调用replace()函数将字符串中的"hello"替换成了"hi"。
replace()函数还可以用来去除字符串中的特定字符,例如:
str = "1,2,3,4,5"
new_str = str.replace(",", "")
print(new_str)
输出结果为:12345
在上面的例子中,我们将字符串中的","替换成了空字符串"",最终得到了一个没有逗号的新字符串new_str。
需要注意的是,replace()函数并不改变原有的字符串,而是创建了一个新的字符串。因此,如果需要改变原有字符串的话,需要重新赋值。例如:
str = "hello world"
str = str.replace("hello", "hi")
print(str)
输出结果为:hi world
总之,replace()函数是Python中非常实用的字符串操作函数,可以帮助我们方便地替换和修改字符串中的子字符串。