Python replace()方法

2021-09-04 15:15 更新

Python replace()方法


描述

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

語法

replace()方法語法:

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

參數(shù)

  • old -- 將被替換的子字符串。
  • new -- 新字符串,用于替換old子字符串。
  • max -- 可選字符串, 替換不超過 max 次

返回值

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

實例

以下實例展示了replace()函數(shù)的使用方法:

#!/usr/bin/python

str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);

以上實例輸出結(jié)果如下:

thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號