日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python-字符串替換

原字符串str:“hello word china”
被替換字符串oldstr:“world”
新替換的字符串newstr:“hi”
替換結(jié)果:hello hi china

實(shí)現(xiàn):

第一種方法:直接調(diào)用replace()

def strreplace(str, oldstr, newstr):

     return str.replace(oldstr,newstr)
第二種方法:利用re模塊正則
 def strreplace(str, oldstr, newstr):
     #先編譯正則
     m=re.compile(oldstr)
#     #替換字符串中的匹配項(xiàng)
     ret=m.sub(newstr,str)
     return ret
第三種方法:實(shí)現(xiàn)替換函數(shù)
# 找到替換字符的開始位置
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:
                    #如果不相等繼續(xù)找,替換字符串的下標(biāo)重新開始,置為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:]

替換結(jié)果

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

結(jié)果:hello hi china



標(biāo)題名稱:創(chuàng)新互聯(lián)Python教程:python-字符串替換
網(wǎng)站URL:http://www.5511xx.com/article/ccehgce.html