Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - replace multiple characters without .replace()

Tags:

python

replace

The task is to transform any string into any string without built-in .replace(). I failed because I forgot that technically space is also a string character. Firstly I transformed this string into the list, but now I see I did it unnecessarily. However, it still doesn't work.

  1. I can replace "cat" into "dog"
  2. I can replace "c" into "dog"

I can't replace "a cat" into "a dog".

I tried with lambda or zip, but I don't really know how to do it. Do you have any clue?

string = "Alice has a cat, a cat has Alice."
old = "a cat"
new = "a dog"

def rplstr(string,old,new):
    """ docstring"""

    result = ''
    for i in string:
        if i == old:
            i = new
        result += i
    return result

print rplstr(string, old, new)
like image 579
Tom Wojcik Avatar asked Jul 18 '26 05:07

Tom Wojcik


1 Answers

This solution avoids string concatenation which can be less efficient. It creates a list of segments to join together at the end:

string = "Alice has a cat, a cat has Alice."
old = "a cat"
new = "a dog"

def rplstr(string, old, new):
    """ docstring"""

    output = []
    index = 0

    while True:
        next = string.find(old, index)

        if next == -1:
            output.append(string[index:])
            return ''.join(output)
        else:
            output.append(string[index:next])
            output.append(new)
            index = next + len(old)

print rplstr(string, old, new)

Giving:

Alice has a dog, a dog has Alice.
like image 128
Martin Evans Avatar answered Jul 20 '26 19:07

Martin Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!