栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python-字符串替换

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/11481.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号