在Python中,replace()
是一個(gè)字符串方法,用于替換字符串中的指定內(nèi)容。
replace()
方法的語(yǔ)法如下:
string.replace(old, new, count)
其中,string
是要進(jìn)行替換操作的字符串,old
是要被替換的內(nèi)容,new
是替換后的內(nèi)容,count
是可選參數(shù),指定要替換的次數(shù)。
下面是一個(gè)使用replace()
方法的示例:
string = "Hello World!"
new_string = string.replace("World", "Python")
print(new_string)
輸出結(jié)果為:Hello Python!
在上述示例中,replace()
方法將字符串中的"World"替換為"Python",并返回替換后的新字符串。
如果要指定替換的次數(shù),可以將count
參數(shù)設(shè)置為大于0的整數(shù)值。例如:
string = "Hello World!"
new_string = string.replace("o", "O", 2)
print(new_string)
輸出結(jié)果為:HellO WOrld!
在上述示例中,replace()
方法將字符串中的前兩個(gè)小寫字母"o"替換為大寫字母"O"。