Python字串replace()
方法返回一個字串的副本,其中出現的舊字元(old
)已被替換為新的(new
)字串,可選地將替換數限制為最大值 - max
。
語法
以下是replace()
方法的語法 -
str.replace(old, new[, max])
參數
- old - 這是要被替換的舊的子字串。
- new - 這是新的子字串,它將替換舊的子字串。
- max - 如果給出此可選參數
max
,則只會替換第一個計數事件。
返回值
- 此方法返回一個字串的副本,其中將所有出現的
old
字串替換為new
字串。 如果給出了可選參數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