今天下午,我的一个粉丝想让我把Replace函数升级一下,那肯定可以啦,于是我就开始Write代码了,不过实在没有想出什么好点子...
直接上代码!!!
def replace(masterstr,replaced_string,replace_string,amount=-1,returntotal=False):
last_search_pos = 0
pos_replaced_string = masterstr.find(replaced_string,last_search_pos)
num = 0 if amount != -1 else -1
total = 0
while pos_replaced_string != -1 and (num < amount if num != -1 else True):
masterstr = masterstr[:pos_replaced_string] + replace_string + masterstr[pos_replaced_string+len(replaced_string):]
last_search_pos = pos_replaced_string+len(replace_string)
pos_replaced_string = masterstr.find(replaced_string,last_search_pos)
if num != -1:
num += 1
if returntotal:
total += 1
if returntotal:
return masterstr,total
elif not returntotal:
return masterstr
我只添加了一个计数功能,运行效果如下:
str = "Hello Python World! Life is short, I use Python!"
print(replace(str,'Python','C++'))
# Hello C++ World! Life is short, I use C++!
print(replace(str,'Python','Java',returntotal=True))
# ('Hello Java World! Life is short, I use Java!', 2)
好啦,这个Replace函数的1.0版本就坐到这里了,,希望大家能私信给我提供建议! 你们的支持就是我前进的动力!
代码下载链接:PythonPySOL之Replace函数(Python内置Replace函数优化升级版)-数据集文档类资源-CSDN下载



