DEV Community

loading...

Simple python string replace without using in-built function

bloodrave_n profile image Pike Msonda ・1 min read

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

Output

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

Discussion

pic
Editor guide