Python 字符串 replace() 方法

實例

替換單詞 "bananas":

txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x)

運行實例

定義和用法

replace() 方法用另一個指定的短語替換一個指定的短語。

注釋:如果未指定其他內容,則將替換所有出現的指定短語。

語法

string.replace(oldvalue, newvalue, count)

參數值

參數 描述
oldvalue 必需。要檢索的字符串。
newvalue 必需。替換舊值的字符串。
count 可選。數字,指定要替換的舊值出現次數。默認為所有的出現。

更多實例

實例

替換所有出現的單詞 "one":

txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)

運行實例

實例

替換前兩次出現的單詞 "one":

txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)

運行實例