不使用regexp实现python replace()函数

2024-06-08 01:35:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图重写python replace()函数的等效函数,而不使用regexp。使用这段代码,我设法使它能够使用单个字符,但不能使用多个字符:

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

有没有人有什么建议,如何使这一工作与一个以上的字符?示例:

^{pr2}$

Tags: 函数代码inselfforbasestringdef
3条回答

让我们尝试使用一些切片(但是您确实应该考虑使用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

以下是一种非常有效的方法:

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

你想变得多聪明?在

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

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

相关问题 更多 >

    热门问题