Python replace()方法


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

語法

replace()方法語法:

 

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

 

參數

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

返回值

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

實例

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

#!/usr/bin/python

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

對當前目錄下的文件夾重命名:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os,sys
Dirpath="./"

for dir in os.listdir(Dirpath):
    if (os.path.isdir(dir)):   #判斷是否是目錄
        #以下兩種方式均可對目錄或文件進行重命名
       # os.rename(dir,'PN_COMMON_'+dir)
        dir.replace('PN_COMMON_'+dir,dir)
print '重命名成功'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM