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

replace函数使用详解
  • 1、不改变原字符串
  • 2、指定替换次数
  • 3、转义符
  • 4、替换列表、元组、字典的元素
  • 5、连续替换

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学习指南


如果想要系统学习Python、Python问题咨询,或者考虑做一些工作以外的副业,都可以扫描二维码添加微信,围观朋友圈一起交流学习。

我们还为大家准备了Python资料和副业项目合集,感兴趣的小伙伴快来找我领取一起交流学习哦!

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

包括:Python激活码+安装包、Python web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程。带你从零基础系统性的学好Python!

👉Python所有方向的学习路线👈

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(全套教程文末领取)

在这里插入图片描述

👉Python学习视频600合集👈

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。

在这里插入图片描述

温馨提示:篇幅有限,已打包文件夹,获取方式在:文末
👉Python70个实战练手案例&源码👈

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

在这里插入图片描述

👉Python大厂面试资料👈

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

在这里插入图片描述

👉Python副业兼职路线&方法👈

学好 Python 不论是就业还是做副业赚钱都不错,但要学会兼职接单还是要有一个学习规划。

在这里插入图片描述

👉 这份完整版的Python全套学习资料已经上传,朋友们如果需要可以扫描下方CSDN官方认证二维码或者点击链接免费领取保证100%免费

  • 21
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值