Python3.4字符串包含 & 集合
2014-04-13 16:06
585 查看
""" 字符串包含 & 集合 """ #方法一: def containsAny(allstr,childstr): for c in allstr: if c in childstr: return True return False allstr = "老毕很帅嘛" childstr = "帅" print(containsAny(allstr,childstr)) # True #方法二: def containsAny2(allstr,childstr): for item in filter(childstr.__contains__,allstr): #python3里直接使用filter return True return False print (containsAny2(allstr,childstr)) # True #方法三: #集合的intersection得到交集 #bool(something),转成布尔型,除了为空返回False,其它只要有值都返回True def containsAny3(allstr,childstr): return bool(set(childstr).intersection(allstr)) print (containsAny3(allstr,childstr)) # True print (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.py True True True False ## 集合联合union: {'嘛', '老', '毕', '很', '帅'} ## 集合差difference: {'老', '毕', '很', '嘛'} ## 集合交集inetersection: {'帅'} ## 返回集合中包含的所有属于一个集合且不属于另外一个的元素: {'老', '毕', '很', '嘛'} {'p', 'n', 'g', 'b', 'a', 'x', 'i', 'e', 'o'} ['a', 'b', 'e', 'g', 'i', 'n', 'o', 'p', 'x']
微信公众帐号: wirelessqa
关于作者:
作者: 毕小朋 | 老 毕 邮箱: wirelessqa.me@gmail.com微博: @WirelessQA 博客: http://blog.csdn.net/wirelessqa
相关文章推荐
- Python3.4字符串包含 & 集合
- Python检测字符串中是否包含某字符集合中的字符
- Python美味食谱:1.8 检测字符串中是否包含某字符集合中的字符
- 找出包含字符串"from"但不含字符串"127.0.0.1"的txt文件 (用SQL+Batch+grep求两个文件集合的差.)
- 【python cookbook】 检查字符串中是否包含某自符集合中的字符
- 001_008 Python 检查字符串中是否包含某字符集合中的字符
- 《Python CookBook2》 第一章 文本 - 检查字符串中是否包含某字符集合中的字符 && 简化字符串的translate方法的使用
- Python检测字符串中是否包含某字符集合中的字符
- python3.4学习笔记(十五) 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python Cookbook 第二版 汉化版 [Recipe 1.8] 检测字符串是否包含特定的字符集合
- python cookbook 学习笔记 -- 1.8 检查字符串中是否包含某字符集合中的字符
- 将字符串按照&切割并放入lsit集合中
- .分析以下需求,并用代码实现 1.定义List集合,存入多个字符串 2.删除集合元素字符串中包含0-9数字的字符串 只要字符串中包含0-9中的任意一个数字就需
- python遍历文件夹找到包含某字符串的文件
- 给一个很长的字符串str 还有一个字符集比如"abc" 找出str 里包含"abc"的最短子串。要求O(n)
- python基础数据结构——列表(list), 元祖(tuple), 字典(dict), 字符串(string), 集合(set) 介绍及相互转换
- 获取查询记录第n行 & 获取字符串包含某字符数量
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)
- Python3学习(一)-基础、数据类型、变量、字符串和编码、list&tuple、if、for、while、dict、set、函数与参数