Python 字串 replace() 方法
定義和用法
replace()
方法用另一個指定的短語替換指定的短語。
注意: 如果沒有指定其他內容,將替換指定短語的所有出現次數。
語法
string.replace(oldvalue, newvalue, count)
引數值
引數 | 描述 |
---|---|
oldvalue | 必需。要搜尋的字串 |
newvalue | 必需。用於替換舊值的字串 |
count | 可選。一個數字,指定要替換舊值的出現次數。預設為所有出現次數 |
更多示例
示例
替換單詞 "one" 的所有出現次數
txt = "one one 曾是賽馬,two two 也是 one。"
x = txt.replace("one", "three")
print(x)
自己動手試一試 »
示例
替換單詞 "one" 的前兩次出現
txt = "one one 曾是賽馬,two two 也是 one。"
x = txt.replace("one", "three", 2)
print(x)
自己動手試一試 »