0

My function has three string parameters i.e. string, search, and replace. If the search parameter is an empty string, then the function is supposed to insert the replaceable parameter before the first parameter, in between each character of the old string, and after the last character of the old string. Here is what I have done so far:

def main():
    s='I am going go'
    x=""
    y='aa'

    print(rep_str(s,x,y))

def rep_str(s, x, y):

    if x in s:
        result = ''
        i = 0
        while i < len(s):
            if s[i : i + len(x)] == x:
                result += y
                i += len(x)
            else:
                result += s[i]
                i += 1


    elif x not in s:
        result= s
    else:
        if x=="":
            result=y        
            for ch in s:
                result+=(ch+y)   

    return result
main()  

I developed each condition separately and put them altogether in the function when I got satisfactory result from them. My last else condition was working fine in a separate run but it is not working in the function module. I don't know what is the problem with the code. I would appreciate, if someone could give me some pointers. Thanks

My output for the last else condition should be:

aaIaa aaaaamaa aagaaoaaiaanaagaa aagaaoaa
5
  • 5
    x is either in s or not in s, what else do you think could happen? :) Commented Feb 16, 2014 at 5:04
  • '' will be in any strings. e.g., '' in 'cobra' → True Commented Feb 16, 2014 at 5:07
  • My last condition is: if the second parameter is an empty string then the new string should start with the third parameter, place third parameter between each character of the old string, and end with the third parameter. Commented Feb 16, 2014 at 5:07
  • The built-in replace method already does this. Can you just use that? Commented Feb 16, 2014 at 5:13
  • No, I can't. Trying to build the replace method from scratch. Commented Feb 16, 2014 at 5:16

1 Answer 1

1

restructure you code:

if x=='':
    pass
elif x in s:
    pass
elif x not in s:
    pass
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help. Didn't think about changing the order. The program is working fine now.Thanks again.
If you have already tested if x in s, then if x not in s is redundant; just use else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.