Python 个人的失误记录之str.replace

mac2022-06-30  22

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('决不能回复', '不要回答')

转载于:https://www.cnblogs.com/23147-2Lemon/p/9153570.html

最新回复(0)