[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
最近的工作经常会碰到对字符串进行去重的操作,这篇文章主要介绍python去掉字符串中重复字符的几种方法,需要的小伙伴可以参考哦。
<>1、直接遍历字符串的方式
# *_* coding : UTF-8 *_* name='王李张李陈王杨张吴周王刘赵黄吴杨' newname='' for char in name:
if char not in newname: newname+=char print (newname) 王李张陈杨吴周刘赵黄
<>2、遍历去重的另一种方式
# *_* coding : UTF-8 *_* name='王李张李陈王杨张吴周王刘赵黄吴杨' newname='' i = len(name)-1
while True: if i >=0: if name[i] not in newname: newname+=(name[i]) i-=1 else:
break print (newname) 杨吴黄赵刘王周张陈李
<>3、将字符串转换成列表的方式(list sort)
# *_* coding : UTF-8 *_* name = '王李张李陈王杨张吴周王刘赵黄吴杨' myname = set(name) print(
myname) newname = list(set(name)) print(''.join(newname)) newname.sort(key=name.
index) print(newname) print(''.join(newname)) {'张', '黄', '刘', '杨', '吴', '周', '陈'
, '赵', '王', '李'} 张黄刘杨吴周陈赵王李 ['王', '李', '张', '陈', '杨', '吴', '周', '刘', '赵', '黄']
王李张陈杨吴周刘赵黄
<>4、根据字符串下标,判断子集
# *_* coding : UTF-8 *_* name='王李张李陈王杨张吴周王刘赵黄吴杨' l = len(name) # 字符串下标总长度 for s
in name: if name[0] in name[1:l]: name = name[1:l] else: name= name[1:l]+name[0]
print(name) 李陈张周王刘赵黄吴杨
<>5、使用 ', '.join(L) ,将列表拼接成我们想要的字符串
# *_* coding : UTF-8 *_* name='王李张李陈王杨张吴周王刘赵黄吴杨' zd={}.fromkeys(name) mylist=
list(zd.keys()) # mylist = list({}.fromkeys(name).keys()) print (''.join(mylist)
) 王李张陈杨吴周刘赵黄
好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。4