user3260982
user3260982

Reputation:

Replace a substring in a string with python

I am trying to replace every instance of a substring in a string using python. The following is the code that I have done and it is giving me some weird result.

def main():
    s='IN GOING GO'
    x='IN'
    y='aa'

    print(rep_str(s,x,y))

def rep_str(s,x,y):
    result=""
    if x in s:
        for i in range(len(s)):
            if s[i:i+len(x)] == x:
                result=result+y
            else:
                result=result+s[i+1:i+len(x)]          

    return result


main()

I am not allowed to use the replace method. In fact, my function is supposed to do what replace function does in python. The following is the output that I am getting.

aa GOIaaG GO

I would appreciate if someone could give me some input about how to change the logic to get the right out put i.e. aa GOaaG GO.

Upvotes: 2

Views: 440

Answers (3)

lessthanl0l
lessthanl0l

Reputation: 1095

If you are allow to use the index() function, you can try this:

def main():
    s='IN GOING GO'
    x='IN'
    y='aa'

    print(rep_str(s,x,y))


def rep_str(s,x,y):
    while x in s:
        s = s[:s.index(x)] + y + s[s.index(x) + len(x):]

    return s


main()

Upvotes: 1

markcial
markcial

Reputation: 9323

If you just want to have the result try with:

import re
re.sub(r'IN','aa','IN GOING GO')

but if you need some logic then you should compare for blocks of same length as the pattern, not char by char

@Zag asnwer is better, because can compare longer patterns and has return when it does not match nothing but if you want to get your code running you need to skip for when you have a match like this :

def rep_str(s,x,y):
    result=""
    skip = False
    if x in s:
        for i in range(len(s)):
            if skip:
                skip = False
                continue
            if s[i:i+2] == x:
                result+=y
                skip = True
            else:
                result+=s[i:i+1] 
        return result
    else:
        return s

but your code won't work when you will call the function with rep_str("A example test","test", "function") for example.

Upvotes: 1

zag
zag

Reputation: 3409

As I mentioned in comments, the mistake is that you are not skipping len(x) characters after match. Also in keyword is quite high-level routine (it does not less than search part of search & replace), so here is fixed version without in:

def rep_str(string, search, replacement):
    result = ''
    i = 0
    while i < len(string):
        if string[i : i + len(search)] == search:
            result += replacement
            i += len(search)
        else:
            result += string[i]
            i += 1
    return result

Upvotes: 3

Related Questions