1. replace() 函数
作用: 替换字符串
语法: replace('需要替换的子串', '新的子串', '替换的次数(可不传)') # 当替换次数不传时,默认全部替换
实例一:
mystr = 'you and me and he' new_str1 = mystr.replace('and', 'or') #没传替换次数,则会把字符串中的所有and子串都替换成or print(new_str1)
结果:
实例二:
mystr = 'you and me and he' new_str2 = mystr.replace('and', 'or', 1) # 传了替换次数1,则只会将字符串中的第一个and替换成or print(new_str2)
结果:
实例三:
mystr = 'you and me and he' new_str3 = mystr.replace('and', 'or', 10) # 替换次数如果超出子串出现的次数,表示替换所有这个子串 print(new_str3)
结果:
注意:
1.调用replace函数后,发现原有字符串的数据并未修改,修改后的数据是replace函数的返回值
2.说明字符串是不可变数据类型
3.数据是否可以改变划分为 可变类型 和不可变类型,而字符串属于不可变类型的数据类型