jwesonga
jwesonga

Reputation: 4383

Implement python replace() function without using regexp

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') 

Upvotes: 3

Views: 5147

Answers (3)

Andrew Clark
Andrew Clark

Reputation: 208545

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:]

Upvotes: 3

MikeyB
MikeyB

Reputation: 3360

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'

Upvotes: 4

Cédric Julien
Cédric Julien

Reputation: 80791

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

Upvotes: 0

Related Questions