Python : Problem recreating replace function

Question:

trying to make a string replace function as a beginner(i don’t want to use an existing function , I am just appliying my knowledge)

word = input("Enter a string : ")

def Ino_String(word,part):
    # if part is in word s will indicate the position where the starting position of part is in word
    # if not s will stay -1
    s = -1

    i = 0
    j = 0
    count = 0
    while i < len(word):
        if word[i] == part[j]:
            count += 1
            j += 1
            i += 1
        else:
            count = 0
            i = i - j + 1
            j = 0
        if count == len(part):
            s = i - len(part)
            break
    return s

def  First_Replace(word,  part, new_part):
    s = Ino_String(word, part)
    if s != -1 :
        new_word = ""
        for i in range(s):
            new_word += word[i]
        for i in range(0, len(new_part)):
            new_word += new_part[i]
        i = s + len(part)
        while i < len(word):
            new_word += word[i]
    else:
        new_word = "Error: the part you want to replace is not in the string"
    return new_word

print(str(Ino_String(word,"hy")))
new_word = First_Replace(word, 'hy', "how")
print(new_word)



input : shy

output : 1
show

but with

input : shyer

output : 1

instead of : 1
shower

Asked By: Moha Med

||

Answers:

It’s actually quite a simple fix. The reason you are only getting 1 as output is because the program loops indefinitely here:

while i < len(word):
    new_word += word[i]

Looking at intermediate outputs, you can quickly see the word becomes showe, showee, showee, …, showeeeee…

All you need to do to fix this program is to increment i:

while i < len(word):
    new_word += word[i]
    i += 1

Also, quite trivially, you can do this to do the same functionality in one line:

word = 'shyer'
match = 'hy'
replace = 'how'
new_word = replace.join(word.split(match))
Answered By: B Remmelzwaal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.