大家好,我是编程猫咪,今天又要跟大家讲python字符串替换函数。
心急的小伙伴,直接看Python replace 示例源码源码:
a="i love love love love you my love lxy" a.replace('love','want') Out[3]: 'i want want want want you my want lxy' a.replace('love','want',2) Out[4]: 'i want want love love you my love lxy'
感谢这几个大佬的文章:
Python的替换函数——replace(),strip(),和re.sub()
str = "hello,china!" str .replace( "hell" , "well" ) print ( str ) |
写代码时发现这样替换之后并没有替换成功。
原因:
在Python中字符串是是不可变对象。
所以字符串使用replace需要重新赋值,生成一个新的对象。
之前没有重新引用,导致该变量 指向的是 以前的对象,实则已经发生变化,只是没有重新引用而已。
所以要想打印出替换后的字符串需要重新赋值,如下:
1
2
3
|
str = "hello,china!" str = str .replace( "hell" , "well" ) print ( str ) |
这样就可以替换成功啦!!
Python中常用的三个“替换”函数是strip(),replace()和re.sub()。下面来说说这三个函数的用法。
I .替换()
基本用法:object。替换(目标xp,替换文本,最大值)
其中,rgExp和replaceText是必选的,max是可选参数,可以省略。
目标表达式引用字符串对象或文本;替换文本是字符串对象或字符串文字;Max是一个数字。对于一个对象,用replaceText替换对象中的每个目标,从左到右的最大次数。
如果您有互联网问题,也可以咨询我,谢谢!如果你也想一起学习人工智能,大神们用什么写作软件欢迎留言交流。
我的其他文章: