Python3 replace()方法

Python3 字串 Python3 字串


描述

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

語法

replace()方法語法:

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

參數

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

返回值

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

實例

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

實例

#!/usr/bin/python3 str = "www.xuhuhu.com" print ("IT研修舊地址:", str) print ("IT研修新地址:", str.replace("xuhuhu.com", "xuhuhu.com")) str = "this is string example....wow!!!" print (str.replace("is", "was", 3))

以上實例輸出結果如下:

IT研修舊地址: www.xuhuhu.com
IT研修新地址: www.xuhuhu.com
thwas was string example....wow!!!

Python3 字串 Python3 字串