共計 424 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,replace() 函數(shù)用于替換字符串中的指定子字符串。它的語法如下:
string.replace(old, new, count)
其中,
- old:需要被替換的子字符串。
- new:用于替換 old 的新字符串。
- count(可選):指定替換的次數(shù)。如果省略該參數(shù),則會替換所有匹配到的子字符串。
replace() 函數(shù)會返回一個新的字符串,該字符串是將原字符串中所有匹配到的子字符串替換為新字符串后的結果。
下面是 replace() 函數(shù)的示例:
string = "Hello, World!"
new_string = string.replace("Hello", "Hi")
print(new_string) # 輸出:Hi, World!
在上面的示例中,replace() 函數(shù)將字符串中的 "Hello" 替換為 "Hi",并將替換后的新字符串賦值給 new_string 變量。最后打印 new_string 的結果為 "Hi, World!"。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完