3

I'm trying to rewrite the equivalent of the python replace() function without using regexp. Using this code, i've managed to get it to work with single chars, but not with more than one character:

def Replacer(self, find_char, replace_char):
    s = []
    for char in self.base_string:
        if char == find_char:
            char = replace_char
        #print char
        s.append(char)
    s = ''.join(s)

my_string.Replacer('a','E')

Anybody have any pointers how to make this work with more than one character? example:

my_string.Replacer('kl', 'lll') 
5
  • 4
    The more important question is why. Commented Nov 15, 2011 at 16:35
  • technically, if you are doing a search like this you will be creating a regular expression. Whether you avoid using python's convenient regex syntax is up to you however Commented Nov 15, 2011 at 16:35
  • 1
    @habitue: Actually, you'll probably do a lot worse. Modern regex engines have all kinds of neat tricks, that simple algorithms are not going to benefit from. Commented Nov 15, 2011 at 16:38
  • 1
    what is wrong with "hlep me".replace("le", "el")? Commented Nov 15, 2011 at 16:49
  • 2
    Rewriting this method gives me in-depth understanding of string operations. Just by look @CedricJulien code I've learned a lot and I appreciate that he took the effort to share the implementation Commented Nov 15, 2011 at 17:19

3 Answers 3

4

How clever are you trying to be?

def Replacer(self, find, replace):
    return(replace.join(self.split(find)))

>>> Replacer('adding to dingoes gives diamonds','di','omg')
'adomgng to omgngoes gives omgamonds'
Sign up to request clarification or add additional context in comments.

Comments

3

Here is a method that should be pretty efficient:

def replacer(self, old, new):
    return ''.join(self._replacer(old, new))

def _replacer(self, old, new):
    oldlen = len(old)
    i = 0
    idx = self.base_string.find(old)
    while idx != -1:
        yield self.base_string[i:idx]
        yield new
        i = idx + oldlen
        idx = self.base_string.find(old, i)
    yield self.base_string[i:]

Comments

0

Let's try with some slices (but you really should consider using the builtin method of python) :

class ReplacableString:
    def __init__(self, base_string):
        self.base_string =base_string

    def replacer(self, to_replace, replacer):
        for i in xrange(len(self.base_string)):
            if to_replace == self.base_string[i:i+len(to_replace)]:
                self.base_string = self.base_string[:i] + replacer + self.base_string[i+len(to_replace):]

    def __str__(self):
        return str(self.base_string)


test_str = ReplacableString("This is eth string")
test_str.replacer("eth", "the")
print test_str

>>> This is the string

2 Comments

Thanks Cedric, I noticed that if u call replacer twice with different params, it replaces the characters based on the last value of self.base_string. Anyway to call replacer and have it change the value of the original self.base_string?
@jwesonga : if you don't want to change the original string, juste create a new_string = self.base_string[:] at the beginning of the replacer method, and then, use it everywhere instead of self.base_string, and at the end, return new_string

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.