Python3 string.replace()方法

replace()方法返回使用 new 來替換所有出現的 old,可選擇更換限制到最大數目的字串的副本。

語法

以下是 replace()方法的語法 -
str.replace(old, new[, max])

參數

  • old -- 這是要替換舊字串

  • new -- 這是新的字串,這將用於取代舊的子字串。

  • max -- 如果給定可選參數max,只有第一個匹配項被取代

返回值

此方法返回所有出現被新的取代舊的子串的字串副本。如果可選參數max給定,只有第一個匹配項取代。

示例

下麵的示例顯示 replace()方法的使用說明。
#!/usr/bin/python3
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))

當我們運行上面的程式,會產生以下結果 -
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string

上一篇: Python3數字 下一篇: Python3字串