python replace() 方法可以将字符串里的字符进行替换。并且返回一个被替换之后的新的字符串,不会修改原字符串。
string.replace(search, rep [,count])
python replace() 方法返回被替换的新字符串。
使用python replace()方法替换字符串中的网址。
>>> '欢迎来到编程领地,我们的官网是https://www.itboolean.com'.replace('https://www.itboolean.com','http://localhost')
'欢迎来到编程领地,我们的官网是http://localhost'
只替换一次。第三个参数是替换次数。下面例子可以看出,第三个参数为1时,只替换了一次。
>>> 'this is a black ,this is a white '.replace('is','IS',1)
'thIS is a black ,this is a white '
>>> 'this is a black ,this is a white '.replace('is','IS')
'thIS IS a black ,thIS IS a white '
替换为大写
>>> str = 'insert into table_name(id) values(1)'
>>> str.replace('insert' ,'INSERT')
'INSERT into table_name(id) values(1)'
注:使用replace替换字符串时,不会修改原字符串。
>>> str
'insert into table_name(id) values(1)'