我试图在不使用regexp的情况下重写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')
答案 0 :(得分:3)
你想要多聪明?
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 :(得分:2)
这是一种非常有效的方法:
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:]
答案 2 :(得分:0)
让我们尝试一些切片(但你真的应该考虑使用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