您好!欢迎来到北极熊

北极熊

热门搜索: 任正非传    神雕侠侣    红楼梦   

01-Python里字符串的常用操作方法--replace()函数

分类:软件开发应用 时间:2022-10-30 20:06 浏览:116
概述
1. replace()  函数作用: 替换字符串语法: replace('需要替换的子串', '新的子串', '替换的次数(可不传)') # 当替换次数不传时,默认全部替换实例一: Pythonmystr = 'you and me and he' new_str1&nbs
内容

1. replace()  函数

作用: 替换字符串

语法: replace('需要替换的子串', '新的子串', '替换的次数(可不传)') # 当替换次数不传时,默认全部替换

实例一:

 Python

mystr = 'you and me and he' new_str1 = mystr.replace('and', 'or')  #没传替换次数,则会把字符串中的所有and子串都替换成or print(new_str1)

结果:  

实例二:

 Python

mystr = 'you and me and he' new_str2 = mystr.replace('and', 'or', 1)  # 传了替换次数1,则只会将字符串中的第一个and替换成or print(new_str2)

结果: 

实例三:

 Python

mystr = 'you and me and he' new_str3 = mystr.replace('and', 'or', 10)    # 替换次数如果超出子串出现的次数,表示替换所有这个子串 print(new_str3)

结果: 

注意:

1.调用replace函数后,发现原有字符串的数据并未修改,修改后的数据是replace函数的返回值

2.说明字符串是不可变数据类型

3.数据是否可以改变划分为 可变类型 和不可变类型,而字符串属于不可变类型的数据类型


评论
资讯正文页右侧广告
联系我们
电话:18936411277
邮箱:1044412291@qq.com
时间:09:00 - 19:00
公众号:北格软件
底部广告