【问题标题】:Implement python replace() function without using regexp在不使用正则表达式的情况下实现 python replace() 函数
【发布时间】:2011-12-29 16:45:12
【问题描述】:

我正在尝试在不使用正则表达式的情况下重写等效的 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') 

【问题讨论】:

  • 更重要的问题是为什么
  • 从技术上讲,如果您进行这样的搜索,您将创建一个正则表达式。是否避免使用 python 方便的正则表达式语法取决于你
  • @habitue:实际上,你可能会做得更糟。现代正则表达式引擎有各种巧妙的技巧,简单的算法不会从中受益。
  • "hlep me".replace("le", "el") 有什么问题?
  • 重写这个方法让我对字符串操作有了更深入的了解。通过查看@CedricJulien 代码,我学到了很多东西,我很感激他努力分享实现

标签: python string function


【解决方案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

【讨论】:

  • 谢谢 Cedric,我注意到如果你用不同的参数调用 replacer 两次,它会根据 self.base_string 的最后一个值替换字符。无论如何调用replacer并让它改变原始self.base_string的值?
  • @jwesonga :如果您不想更改原始字符串,只需在替换方法的开头创建一个new_string = self.base_string[:],然后在任何地方使用它而不是self.base_string,然后最后,return new_string
【解决方案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:]

【讨论】:

    【解决方案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'
    

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 2021-07-13
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 2021-06-14
      • 1970-01-01
      相关资源
      最近更新 更多