共計 514 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,replace()
是一個字符串方法,用于替換字符串中的指定內(nèi)容。
replace()
方法的語法如下:
string.replace(old, new, count)
其中,string
是要進行替換操作的字符串,old
是要被替換的內(nèi)容,new
是替換后的內(nèi)容,count
是可選參數(shù),指定要替換的次數(shù)。
下面是一個使用 replace()
方法的示例:
string = "Hello World!"
new_string = string.replace("World", "Python")
print(new_string)
輸出結(jié)果為:Hello Python!
在上述示例中,replace()
方法將字符串中的 "World" 替換為 "Python",并返回替換后的新字符串。
如果要指定替換的次數(shù),可以將 count
參數(shù)設置為大于 0 的整數(shù)值。例如:
string = "Hello World!"
new_string = string.replace("o", "O", 2)
print(new_string)
輸出結(jié)果為:HellO WOrld!
在上述示例中,replace()
方法將字符串中的前兩個小寫字母 "o" 替換為大寫字母 "O"。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完