3

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)
2
  • 2
    did you try re.sub? Commented Feb 8, 2016 at 18:08
  • Hmm... given strings are immutable, really the assignment doesn't make sense since you could just return new... Commented Feb 8, 2016 at 18:11

4 Answers 4

5

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.
Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

>>>Alice hasa a dogt, a dog hasa aAalaiacaea.a That's what I have, but probably it's just the matter of a few small things in the code. A cat was changed into a dog. I'll read your code few times. Thank you.
@TomWojcik Ah, yes, I missed a line. Updated.
2

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

2 Comments

I believe if the new string is longer than the old string, then letters on the end of the string won't get tested. Or if the new string contains the old string.
You, sir, know how to code. Thank you. Works perfect and it's relatively simple.
2

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

1 Comment

Indeed, it does work but my tutor said that we cannot use any built-in methods, nor regular expressions.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.