python中替換函數是replace(),該函數語法格式為:“str.replace(old, new[, max])”,它主要是將字符串中的舊字符串替換成新字符串,如果指定第三個參數max,則替換不超過max次。
具體使用步驟:
1、首先打開python編輯器,新建一個python項目。
2、在python項目中定義一個字符串。
str = "this is string example....wow!!! this is really string";
3、最后再通過replace()函數進行替換字符串即可。
print str.replace("is", "was");
完整示例代碼:
#!/usr/bin/python
#www.5655pk.com
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
擴展知識:
strip() #刪除指定字符串函數
re.sub() #通過正則表達式替換