- 1. replace 替換列表中元素的部分內容后返回列表
- 2018.06.08
- 錯誤操作 -- 這樣並不能改變改變列表內的元素
-
data = ['1', '3', '決不能回復---它'] data[2].replace('決不能回復', '不要回答')
- 分析--replace 替換不是在原來的位置完成的
- 驗證 內存地址是否相同,實際是內存地址不同,所以替換產生了一個新的。
-
data = ['1', '3', '決不能回復---它'] other = data[2].replace('決不能回復', '不要回答') print(id(other)) >>>> 2432701696016 print(id(data[2])) >>>>>2432701138144
- 查看文檔
- 返回包含所有出現的子字符串 old 的字符串的副本,替換為 new。如果給出了可選參數 count,則只替換第一個 count 出現。
- Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
- 正確操作
-
data = ['1', '3', '決不能回復---它'] data[2] = data[2].replace('決不能回復', '不要回答')