老卫带你学—python实现replace函数功能
在我们python中是内置了replace函数功能的,那如何不使用replace函数来实现该功能呢
思想:
设置滑动窗口,通过滑动窗口比较子串和待替换字符串,如果相等,则进行替换
python代码:
def replace(str1,k1,k2):
str1=[x for x in str1]
n=len(str1)
result=str1
for i in range(n):
for j in range(i):
if str1[j:i]==list(k1):
result[j:i]=list(k2)
return "".join(result)
print(replace("aaabbbccccbbbbccccccc", "bbb", "eee"))
print("aaabbbccccbbbbccccccc".replace("bbb", "eee"))
这里注意一下,字符串str本身不能进行切片替换,我们需要将其转为list,再进行切片替换
查看输出:
aaaeeecccceeebccccccc
aaaeeecccceeebccccccc

230

被折叠的 条评论
为什么被折叠?



