Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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') 
like image 377
jwesonga Avatar asked Apr 01 '26 16:04

jwesonga


2 Answers

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'
like image 106
MikeyB Avatar answered Apr 04 '26 10:04

MikeyB


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:]
like image 29
Andrew Clark Avatar answered Apr 04 '26 10:04

Andrew Clark