python-字符串替换

402次阅读
没有评论

python-字符串替换

原字符串str:“hello word china” 被替换字符串oldstr:“world” 新替换的字符串newstr:“hi” 替换结果:hello hi china

实现:

第一种方法:直接调用replace()

def strreplace(str, oldstr, newstr):

     return str.replace(oldstr,newstr)
第二种方法:利用re模块正则
 def strreplace(str, oldstr, newstr):
     #先编译正则
     m=re.compile(oldstr)
#     #替换字符串中的匹配项
     ret=m.sub(newstr,str)
     return ret
第三种方法:实现替换函数
# 找到替换字符的开始位置
def getindex(str, key):
    n1 = len(str)
    n2 = len(key)
    i = 0
    j = 0
    while i < n1:
        if str[i] != key[j]:
            i = i + 1
        else:
            # index为开始位置
            index = i
            while j < n2:
                if str[i] == key[j]:
                    i += 1
                    j += 1
                else:
                    #如果不相等继续找,替换字符串的下标重新开始,置为0
                    j = 0
                    break
            return index
    return -1

def strreplace(str, oldstr, newstr):
    index = getindex(str, oldstr)
    # print(index)
    step = index + len(oldstr)
    return str[:index] + newstr + str[step:]

替换结果

str = strreplace('hello world china', 'world', 'hi')

结果:hello hi china

 

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-19发表,共计1046字。
新手QQ群:570568346,欢迎进群讨论 Python51学习