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.數據是否可以改變划分為 可變類型 和不可變類型,而字符串屬於不可變類型的數據類型