Python替换字符串replace()函数使用方法详解

 更新时间:2023年07月26日 10:39:52   作者:士别三日wyx  
Python中的replace()方法是把字符串中的old(旧字符串)替换成new(新字符串),如果指定第三个参数max,则替换次数不超过max次(将旧的字符串用心的字符串替换不超过max次,本文就给大家讲讲Python replace()函数的使用方法,需要的朋友可以参考下

replace() 可以「替换」字符串中的内容

语法

string.replace( old, new, count )

参数

  • old :(必选,字符串类型)被替换的字符串
  • new :(必选,字符串类型)替换后的字符串
  • count :(可选,整型)替换的次数

返回值

  • 返回替换后的新字符串

实例:将字符串中的 “hello” 替换成 “world”

str1 = 'hello hello hello hello world'
str2 = str1.replace('hello', 'world')
print(str2)

输出:

world world world world world

1、不改变原字符串

因为Python中的字符串是「不可变」的,所以 replace() 不会改变原字符串的内容,而是返回一个新的字符串。

我们分别打印替换前、后的两个字符串「内容」和「内存地址」。

str1 = 'hello hello hello hello world'
print(id(str1))
str2 = str1.replace('hello', 'world')
print(str1, id(str1))
print(str2, id(str2))

输出:

2834751121168
hello hello hello hello world 2834751121168
world world world world world 2834751121568

可以看到,原字符串的内容和内存地址没有发生变化。

2、指定替换次数

「不指定」次数,默认替换「所有」匹配到的字符串

str1 = 'hello_1 hello_2 hello_3 hello_4'
print(str1.replace('hello', 'world'))

输出:

world_1 world_2 world_3 world_4

替换次数为「正数」时,按照从左到右的顺序替换,设置几次就替换几次

str1 = 'hello_1 hello_2 hello_3 hello_4'
print(str1.replace('hello', 'world', 1))
print(str1.replace('hello', 'world', 3))

输出:

world_1 hello_2 hello_3 hello_4
world_1 world_2 world_3 hello_4

替换次数为「负数」时,无论负几,都会替换所有匹配到的内容

str1 = 'hello_1 hello_2 hello_3 hello_4'
print(str1.replace('hello', 'world', -1))
print(str1.replace('hello', 'world', -3))

输出:

world_1 world_2 world_3 world_4
world_1 world_2 world_3 world_4

指定的次数必须是「整型」,否则会报错 TypeError: ‘str’ object cannot be interpreted as an integer

或者 TypeError: integer argument expected,

3、转义符

字符串中的转义符不会打印出来,但 replace() 可以替换这些转义符,比如替换换行符\n

str1 = 'hello world\n'
print(str1)
print(str1.replace('\n', ' new'))

输出:

hello world
hello world new

从结果可以看到,替换前会换行,替换后不会换行,因为转义符被替换掉了。

4、替换列表、元组、字典的元素

对「列表」中的元素使用 replace() ,可以使用下面这种方式

arr = ['hello', 'hello', 'hello']
print([string.replace('hello', 'world') for string in arr])

输出:

['world', 'world', 'world']

这种方式本质上是生成了一个「新数组」,我们可以看一下内存地址

arr = ['hello', 'hello', 'hello']
print(id(arr))
print(id([string.replace('hello', 'world') for string in arr]))

输出:

1658941612416
1658941612544

或者使用「循环」的方式替换列表中的元素,这种方式不会生成新数组,替换前、后的内存地址是一样的。

arr1 = ['hello', 'hello', 'hello']
print(arr1, id(arr1))
for a in range(len(arr1)):
    arr1[a] = arr1[a].replace('hello', 'world')
print(arr1, id(arr1))

输出:

['hello', 'hello', 'hello'] 1672076599552
['world', 'world', 'world'] 1672076599552

替换「元祖」中的元素,需要先转成列表,再循环替换,替换完成再转回元组,这种方式同样会改变内存地址。

tu = ('hello', 'hello', 'hello')
print(id(tu))
arr1 = list(tu)
for a in range(len(arr1)):
    arr1[a] = arr1[a].replace('hello', 'world')
tu = tuple(arr1)
print(tu, id(tu))

输出:

2255689005696
('world', 'world', 'world') 2255689005824

替换「字典」的值,直接循环替换

dic = {'key1': 'zhangsan', 'key2': 'lisi'}
for a in dic:
    dic[a] = dic[a].replace('zhangsan', 'new')
print(dic)

输出:

{'key1': 'new', 'key2': 'lisi'}

5、连续替换

因为 replace() 返回的是一个字符串,所以我们可以对返回的结果再次replace(),比如下面这样:

str1 = 'zhangsan lisi wangwu'
print(str1.replace('zhangsan', 'new').replace('lisi', 'new'))

输出:

new new wangwu

有多个内容需要替换时,可以使用这种简化的方式。

到此这篇关于Python替换字符串replace()函数使用方法详解的文章就介绍到这了,更多相关Python replace()函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • appium+python自动化配置(adk、jdk、node.js)

    appium+python自动化配置(adk、jdk、node.js)

    这篇文章主要介绍了appium+python自动化配置(adk、jdk、node.js),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Pytest测试报告工具Allure用法介绍

    Pytest测试报告工具Allure用法介绍

    这篇文章介绍了Pytest测试报告工具Allure的用法,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • Python3enumrate和range对比及示例详解

    Python3enumrate和range对比及示例详解

    这篇文章主要介绍了Python3enumrate和range对比及示例详解,在Python中,enumrate和range都常用于for循环中,enumrate函数用于同时循环列表和元素,而range()函数可以生成数值范围变化的列表,而能够用于for循环即都是可迭代的,需要的朋友可以参考下
    2019-07-07
  • Python中datetime模块参考手册

    Python中datetime模块参考手册

    Python处理时间和日期方面的模块,主要就是datetime、time、calendar三个模块的使用。下面这篇文章主要给大家介绍的是Python中的datetime模块,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-01-01
  • Python基于docker部署的Mysql备份查询脚本

    Python基于docker部署的Mysql备份查询脚本

    这篇文章主要来和大家分享Python基于docker部署的Mysql备份查询的脚本,文中的示例代码讲解详细,有需要的小伙伴可以跟随小编一起了解下
    2024-04-04
  • 详解Python数据可视化编程 - 词云生成并保存(jieba+WordCloud)

    详解Python数据可视化编程 - 词云生成并保存(jieba+WordCloud)

    这篇文章主要介绍了Python数据可视化编程 - 词云生成并保存(jieba+WordCloud),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • 正则表达式在Python中的应用小结

    正则表达式在Python中的应用小结

    正则表达式是一种强大的文本模式匹配工具,它可以帮助我们快速地检索、替换或提取字符串中的特定模式,在本文中,我将通过一些示例代码,详细介绍正则表达式在Python中的应用,感兴趣的朋友一起看看吧
    2024-07-07
  • 使用Python内置模块与函数进行不同进制的数的转换

    使用Python内置模块与函数进行不同进制的数的转换

    这篇文章主要介绍了使用Python内置模块与函数进行不同进制的数的转换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • Python qqbot 实现qq机器人的示例代码

    Python qqbot 实现qq机器人的示例代码

    这篇文章主要介绍了Python qqbot 实现qq机器人的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • Python自动发邮件脚本

    Python自动发邮件脚本

    本文主要介绍了Python自动发邮件脚本的相关知识。具有很好的参考价值,下面跟着小编一起来看下吧
    2017-03-03

最新评论