1. 程式人生 > 實用技巧 >Python replace()方法

Python replace()方法

描述

Python replace() 方法把字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個引數max,則替換不超過 max 次。

語法

replace()方法語法:

str.replace(old, new[, max])

引數

old -- 將被替換的子字串。

new -- 新字串,用於替換old子字串。

max -- 可選字串, 替換不超過 max 次。

返回值

返回字串中的 old(舊字串) 替換成 new(新字串)後生成的新字串,如果指定第三個引數max,則替換不超過 max 次。

例項

以下例項展示了replace()函式的使用方法:

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

replace 不會改變原 string 的內容

例項:

temp_str = 'this is a test'
print(temp_str.replace('is','IS')
print(temp_str)

結果為:

thIS IS a test
this is a test