Python3.4字符串包含 & 集合

来源:互联网 发布:盛势网络剧微博 编辑:程序博客网 时间:2024/04/28 06:33
"""字符串包含 & 集合"""#方法一:def containsAny(allstr,childstr):for c in allstr:if c in childstr: return Truereturn Falseallstr = "老毕很帅嘛"childstr = "帅"print(containsAny(allstr,childstr))  # True#方法二:def containsAny2(allstr,childstr):for item in filter(childstr.__contains__,allstr): #python3里直接使用filterreturn Truereturn Falseprint (containsAny2(allstr,childstr)) # True#方法三:#集合的intersection得到交集#bool(something),转成布尔型,除了为空返回False,其它只要有值都返回Truedef containsAny3(allstr,childstr):return bool(set(childstr).intersection(allstr))print (containsAny3(allstr,childstr)) # Trueprint (containsAny3(allstr,"赞")) # False#===========================集合拓展:===========================print ("## 集合联合union: " )print (set(childstr).union(set(allstr))) #{'嘛', '很', '毕', '老', '帅'}print ("## 集合差difference: ")print (set(allstr).difference(set(childstr))) #{'嘛', '很', '毕', '老'}print("## 集合交集inetersection: ")print (set(allstr).intersection(set(childstr))) #{'帅'}print ("## 返回集合中包含的所有属于一个集合且不属于另外一个的元素: ")print (set(allstr).symmetric_difference(set(childstr))) #{'老', '毕', '很', '嘛'}#集合的不重复性test_str = "bixiaoxiaoxiaopengpeng"#转换成集合strset = set(test_str)print(strset) #{'i', 'e', 'o', 'x', 'a', 'g', 'p', 'b', 'n'}#给集合排序strlist = list(strset) #先将集合转成list#sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数strlist.sort()  #sort没有返回值,但是会对列表的对象进行排序。print(strlist)  # ->['a', 'b', 'e', 'g', 'i', 'n', 'o', 'p', 'x']


运行结果:

bixiaopeng@bixiaopengtekiMacBook-Pro python_text$ python text_checkcontains.pyTrueTrueTrueFalse## 集合联合union:{'嘛', '老', '毕', '很', '帅'}## 集合差difference:{'老', '毕', '很', '嘛'}## 集合交集inetersection:{'帅'}## 返回集合中包含的所有属于一个集合且不属于另外一个的元素:{'老', '毕', '很', '嘛'}{'p', 'n', 'g', 'b', 'a', 'x', 'i', 'e', 'o'}['a', 'b', 'e', 'g', 'i', 'n', 'o', 'p', 'x']

微信公众帐号: wirelessqa

wirelessqa

关于作者:

作者: 毕小朋 | 老 毕 邮箱: wirelessqa.me@gmail.com

微博: @WirelessQA 博客: http://blog.csdn.net/wirelessqa





1 0