Q:

Index Overflow - Python

I'm used to code in C, and I'm trying to pass the functions I implemented to Python, and I'm new to the language. This function here works perfecly in C, but it's giving me overflow when I enter the following input:
"Rafael
af
rosa"
What can be wrong?
def substr(str1,str2,str3):
    """The function analyzes a string and replaces a part with another."""
    #str1 is the function which the part will be replaced.
    #str2 is the part to be replaced.
    #str3 is the string that will replace str2 in str1.
    n=0
    while n<len(str1):
        if str1[n]==str2[0]:
            k=0
            l=n
            d=1
            while k<len(str2):
                if str1[l]!=str2[k]:
                    d=0
                    break
                k+=1
                l+=1
            if d==1:
                if len(str2)>len(str3):
                    l=0
                    while l<(len(str2)-len(str3)):
                        k=n
                        while str1[k]!=0:
                            str1[k]=str1[k+1]
                            k+=1
                        l+=1
                if len(str3)>len(str2):
                    l=0
                    while l<(len(str3)-len(str2)):
                        k=len(str1)
                        while k>=n:
                            str1[k+1]=str1[k]
                            k-=1
                        l+=1
                k=n
                l=0
                while l<len(str3):
                    str1[k]=str3[l]
                    k+=1
                    l+=1
                n+=len(str3)-1
        n+=1
    return str1

str1=input()
str2=input()
str3=input()
strf=substr(str1,str2,str3)
print(strf)

A:

Or you can simply do:
'Rafael'.replace('af', 'rosa')

