当前位置: 移动技术网 > IT编程>脚本编程>Python > 20190118-自定义实现replace方法

20190118-自定义实现replace方法

2019年01月19日  | 移动技术网IT编程  | 我要评论

徐闻县第一中学,千方百计歌词,陕西七套在线直播

1.自定义实现replace方法

python replace() 方法把字符串中的 old(旧字符串) 替换成 neange(新字符串),如果指定第三个参数max,则替换不超过 max 次。
考虑old与nein的长度不一样的情况,如old = 'is';new = 'was'

思路:

1.先找出字符串中old字符的index,考虑可能出现多次的情况使用一个列表replace_str_index_in_s存储old_str的index

2.使用result列表存储替换后的新的字符串,考虑result的生成方式为:

  2.1 从原有字符串的第0位开始,如果index不在replace_str_index_in_s中,则result+=s[i],然后查看i+1,i+2...

  2.2 如果index在replace_str_index_in_s中,则result+=new_str,此时需要注意的一点是新的i的位置位i+len(old_str)而非i+1

  2.3 考虑不知下一个i的值为i+1还是i+len(old_str),因此用while语句来实现

3. 考虑给定max的情况使用count来计数,当count<max的时候替换,当count>max的时候不替换

def customize_replace(s,old_str,new_str,max=none):
    result =''
    #存储新的字符串
    replace_str_index_in_s =[]
    #存储old_str的index
    for i in range(len(s)):
        if s[i:i+len(old_str)]==old_str:
            replace_str_index_in_s.append(i)
    j=0
    if max==none:
        while j <len(s):
            #遍历s[j],j的值不是按序+1,因此用while循环
            if j in replace_str_index_in_s:
                result+=new_str
                j+=len(old_str)
            else:
                result+=s[j]
                j+=1
    else:
        count =0
        #统计替换次数
        while j <len(s):
            if count <max and j in replace_str_index_in_s:
                print('if执行',j,result)
                result+=new_str
                j+=len(old_str)
                count+=1
            else:
                print('else执行',j,result)
                result+=s[j]
                j+=1
    return result

tips:有一种特殊情况如s2='addbbdddbbbddbb##bb#'有3个b的情况下替换的old_str为bb的时候,因此replace_str_index_in_s里面的index可能结果为[3,8,9,13,17],但是明显第9位不会进行替换,因为此处需要用count来计数而不能写做replace_str_index_in_s[:max],这种写法的情况下会有替换次数不足max的情况,错误情况如max =3,那么replace_str_index_in_s[:3] = [3,8,9],但是第9位不会替换,因此实际替换次数为2,因此不能用这种写法

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网