DEV Community

Pike Msonda
Pike Msonda

Posted on

Simple python string replace without using in-built function

A friend asked if I could replicate the python in-built string replace function.

Not as robust of course but I thought I should give it a try.

Below is my take.

Any ideas to improve this are welcome.

def replace(strng, substr, rplstr): 
    if substr not in strng:
        return strng

    low_index = strng.find(substr) # get lowest index of substring
    high_index = low_index + len(substr) # evaluate the highest index of substring

    return replace(strng[:low_index]+ rplstr + strng[high_index:], substr, rplstr) 

Enter fullscreen mode Exit fullscreen mode


print(replace("Hello World Hello World", "llo", "@@"))
He@@ World He@@ World
Enter fullscreen mode Exit fullscreen mode

Top comments (0)