Tom Wojcik February 2016

Python - replace multiple characters without .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)

Answers


Brendan Abel February 2016

You can step through the string, one character at a time, and test to see if it matches with the first character of your old string. If it matches, keep a reference to the index, then continue stepping through the characters, now trying to match against the 2nd char of old. Keep going until you match the entire old string. If the full match succeeds, use the index of the first character match and the length of the old string to create a new string with the new string inserted into it.

def replstr(orig, old, new):
    i = 0
    output = ''
    temp = ''
    for c in orig:
        if c == old[i]:
            i += 1
            temp += c
        else:
            i = 0
            if temp:
                output += temp
                temp = ''
            output += c
        if len(temp) == len(old):
            output += new
            temp = ''
            i = 0
    else:
        if temp:
            output += temp


pp_ February 2016

You can do it with slices:

def rplstr(string, old, new):
    for i in xrange(len(string)):
        if old == string[i:i+len(old)]:
            string = string[:i] + new + string[i+len(old):]
    return string


Martin Evans February 2016

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.


Prashanth February 2016

You can do it in a simple and tiny way by using regular expressions.

import re

my_string = "Alice has a cat, a cat has Alice."
new_string = re.sub(r'a cat', 'a dog', my_string)
print new_string

Post Status

Asked in February 2016
Viewed 1,129 times
Voted 4
Answered 4 times

Search




Leave an answer