新聞中心
這里有您想知道的互聯(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網(wǎng)站欄目:創(chuàng)新互聯(lián)Python教程:python-字符串替換
分享網(wǎng)址:http://m.fisionsoft.com.cn/article/ccehgce.html


咨詢
建站咨詢
