DEV Community

Tshihab07
Tshihab07

Posted on

Replacing a substring in a string with another string using python without built-in function

"""
suppose a text txt is given. we want to replace the first occurrence of the pattern P1 by another pattern P2.
REPLACE(txt, P1, P2)
"""

def REPLACE(txt, p1, p2):
    if p1 not in txt:
        return "Pattern not found"

    # getting index of the pattern
    idx = txt.find(p1)

    # initialize variables to store new string
    temp_txt = ""
    new_txt = ""


    # deleting substring from the text
    for i in range(len(txt)):
        if i < idx or i >= idx + len(p1):
            temp_txt += txt[i]


    # adding p2 in txt as replacement
    for i in range(len(temp_txt)):
        if i == idx-1:
            new_txt += temp_txt[i]

            for j in range(len(p2)):
                new_txt += p2[j]

        else:
            new_txt += temp_txt[i]


    return new_txt
Enter fullscreen mode Exit fullscreen mode

Top comments (0)