在不使用正则表达式的情况下实现Python的replace()函数

3 投票
3 回答
4924 浏览
提问于 2025-04-17 06:22

我正在尝试自己写一个和Python的replace()函数功能相同的代码,但不使用正则表达式。用我现在的代码,我已经能处理单个字符的替换,但对于多个字符的替换就不行了:

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

有没有人能给我一些建议,怎么才能让这个代码支持多个字符的替换呢?比如:

my_string.Replacer('kl', 'lll') 

3 个回答

4

这里有一种方法,应该挺高效的:

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

你想要多聪明呢?

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

>>> Replacer('adding to dingoes gives diamonds','di','omg')
'adomgng to omgngoes gives omgamonds'
1

我们来试试用一些切片的方法(不过你真的应该考虑使用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

撰写回答