Python replace函数

replace函数

字符串处理函数
语法:str.replace(old,new[,max])

  • old需要进行更换的旧子串
  • new新的子串,将取代旧的子字符串(子串可以为空)
  • max如果可选参数max值给出,表示出现前max的次数的子串被替换
str="monkey likes lion,wow!!!monkey likes lion very much!!"
print(str.replace("li","ha"))
print(str.replace("li","ha",3))
print(str.replace('li',''))
print(str)

输出结果

monkey likes lion,wow!!!monkey likes lion very much!!
monkey hakes haon,wow!!!monkey hakes lion very much!!
monkey kes on,wow!!!monkey kes on very much!!
monkey likes lion,wow!!!monkey likes lion very much!!

运行结果来看,replace函数不会改变原始字符串的值,如果需要使用替换后的字符串,需要将其重新赋值给一个新的变量

你可能感兴趣的:(Python)