搜索
写经验 领红包
 > 职场

pytho扩展方法(pytho的扩展性)

导语:扩展python3的replace()方法

python 扩展方法(python的扩展性)

扩展后的方法说明

扩展后的replace()方法的功能:去掉字符串中的指定字符串,并返回去掉后的子字符串,替换时可设置是否区分大小写

传参说明

myString:原字符串oldSubStr:要替换的子字符串newSubStr:替换后的子字符串count:要替换的次数,默认为-1(负数-全部替换,0-不替换,1-替换第1个,n-替换前n个)caseSensitive:1-区分大小写,其他-不区分大小写

源码

def myReplace(myString, oldSubStr, newSubStr, count=-1, caseSensitive=&39;):     oldSubStr为空时不做替换,直接返回原字符串    if oldSubStr == &39;:        return myString    39;1& 不区分大小写时,oldSubStr在myString中不存在    39;1&39;flag& 不区分大小写时,oldSubStr在myString中存在    oldSubStr = oldSubStr.lower()    if count == 0:        return myString    elif count < 0:        for i in tem[&39;]:            myString = oldSubStr.join(myString.split(myString[i:i + len(oldSubStr)]))    else:        for i in tem[&39;][:count]:            myString = oldSubStr.join(myString.split(myString[i:i + len(oldSubStr)]))    myString = myString.replace(oldSubStr, newSubStr, count)    return myString

测试结果

39;__main__&39;结果1:&39;China will be a STRONG country!&39;will&39;must&39;0&39;结果2:&39;China will be a STRONG country!&39;will&39;must&39;0&39;结果3:&39;China will be a STRONG country!&39;strong&39;stronger&39;1&39;结果4:&39;China will be a STRONG country!&39;strong&39;stronger&39;0&39;结果5:&39;China will be a STRONG country!&39;t&39;-t-&39;0&39;结果6:&39;China will be a STRONG country!&39;t&39;-t-&39;0&39;结果7:&39;China will be a STRONG country!&39;!&39;&39;0&39;结果8:&39;China will be a STRONG country!&39;&39;&39;0&39;结果9:&39;China will be a STRONG country!&39;abc&39;&39;0&39;结果10:&39;China will be a STRONG country!&39; &39;&39;0&39;结果11:&39;China will be a STRONG country!&39; &39;&39;0&39;结果12:&39;China will be a STRONG country!&39; &39;&39;0& 结果结果1: China must be a STRONG country!结果2: China will be a STRONG country!结果3: China will be a STRONG country!结果4: China will be a stronger country!结果5: China will be a S-t-RONG country!结果6: China will be a S-t-RONG coun-t-ry!结果7: China will be a STRONG country结果8: China will be a STRONG country!结果9: China will be a STRONG country!结果10: ChinawillbeaSTRONGcountry!结果11: Chinawillbe a STRONG country!结果12: ChinawillbeaSTRONGcountry!

本文内容由小萱整理编辑!