xxlxxl 发表于 2020-10-13 14:19:19

定义一个函数,与replace相同功能

如何在不用replace函数的情况下达到replace的功能?
print(replace('abc def abc', 'def', 'abc')) # abc abc abc
print(replace('abcabcabc', 'abc', 'hi'))    # hihihi
print(replace('This is out of control!', 'out of control!', 'better!')) # This is better!

冬雪雪冬 发表于 2020-10-13 14:25:16

def replace(string, old, new):
    return new.join(string.split(old))

kogawananari 发表于 2020-10-13 14:27:59

用re.sub如何(滑稽{:10_246:}

不然得手写滑动窗口算法了

这个问题发数据结构和算法板块更好

xxlxxl 发表于 2020-10-13 14:42:53

kogawananari 发表于 2020-10-13 14:27
用re.sub如何(滑稽

不然得手写滑动窗口算法了


我看了下题目,不能用re.sub,题目意思是让我用纯loop写,头秃。

xxlxxl 发表于 2020-10-13 14:45:24

冬雪雪冬 发表于 2020-10-13 14:25


有没有不用join,用loop的方法啊

冬雪雪冬 发表于 2020-10-13 15:01:54

xxlxxl 发表于 2020-10-13 14:45
有没有不用join,用loop的方法啊

def replace(string, old, new):
    lst = string.split(old)
    s = lst
    for each in lst:
      s += new + each
    return s

hrp 发表于 2020-10-13 15:06:03

def replace(string, old, new):
    while old in string:
      ind = string.index(old)
      string = string[:ind] + new +string
    return string

print(replace('abc def abc', 'def', 'abc')) # abc abc abc
print(replace('abcabcabc', 'abc', 'hi'))    # hihihi
print(replace('This is out of control!', 'out of control!', 'better!')) # This is better!
页: [1]
查看完整版本: 定义一个函数,与replace相同功能