python replace()字符串替换

文章发布于 2023-05-26

python replace() 方法

python replace() 方法可以将字符串里的字符进行替换。并且返回一个被替换之后的新的字符串,不会修改原字符串。

replace()方法语法

string.replace(search, rep [,count])
  • search 被替换的子串。
  • rep 新的子串,新子串替换掉search的子串。
  • 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)'