判断字符串是否包含子串,居然有七种方法?

1. 使用 in 和 not

创新互联专注于企业全网整合营销推广、网站重做改版、洛浦网站定制设计、自适应品牌网站建设、html5成都做商城网站、集团公司官网建设、成都外贸网站建设公司、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为洛浦等各大城市提供网站开发制作服务。

inin 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。

使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下:

 
 
 
  1. >>> "llo" in "hello, python" 
  2. True 
  3. >>> 
  4. >>> "lol" in "hello, python" 
  5. False 

2. 使用 find 方法

使用 字符串 对象的 find 方法,如果有找到子串,就可以返回指定子串在字符串中的出现位置,如果没有找到,就返回 -1

 
 
 
  1. >>> "hello, python".find("llo") != -1 
  2. True 
  3. >>> "hello, python".find("lol") != -1 
  4. False 
  5. >> 

3. 使用 index 方法

字符串对象有一个 index 方法,可以返回指定子串在该字符串中第一次出现的索引,如果没有找到会抛出异常,因此使用时需要注意捕获。

 
 
 
  1. def is_in(full_str, sub_str): 
  2.     try: 
  3.         full_str.index(sub_str) 
  4.         return True 
  5.     except ValueError: 
  6.         return False 
  7.  
  8. print(is_in("hello, python", "llo"))  # True 
  9. print(is_in("hello, python", "lol"))  # False 

4. 使用 count 方法

利用和 index 这种曲线救国的思路,同样我们可以使用 count 的方法来判断。

只要判断结果大于 0 就说明子串存在于字符串中。

 
 
 
  1. def is_in(full_str, sub_str): 
  2.     return full_str.count(sub_str) > 0 
  3.  
  4. print(is_in("hello, python", "llo"))  # True 
  5. print(is_in("hello, python", "lol"))  # False 

5. 通过魔法方法

在第一种方法中,我们使用 in 和 not in 判断一个子串是否存在于另一个字符中,实际上当你使用 in 和 not in 时,Python 解释器会先去检查该对象是否有 __contains__ 魔法方法。

若有就执行它,若没有,Python 就自动会迭代整个序列,只要找到了需要的一项就返回 True 。

示例如下:

 
 
 
  1. >>> "hello, python".__contains__("llo") 
  2. True 
  3. >>> 
  4. >>> "hello, python".__contains__("lol") 
  5. False 
  6. >>> 

这个用法与使用 in 和 not in 没有区别,但不排除有人会特意写成这样来增加代码的理解难度。

6. 借助 operator

operator模块是python中内置的操作符函数接口,它定义了一些算术和比较内置操作的函数。operator模块是用c实现的,所以执行速度比 python 代码快。

在 operator 中有一个方法 contains 可以很方便地判断子串是否在字符串中。

 
 
 
  1. >>> import operator 
  2. >>> 
  3. >>> operator.contains("hello, python", "llo") 
  4. True 
  5. >>> operator.contains("hello, python", "lol") 
  6. False 
  7. >>>  

7. 使用正则匹配

说到查找功能,那正则绝对可以说是专业的工具,多复杂的查找规则,都能满足你。

对于判断字符串是否存在于另一个字符串中的这个需求,使用正则简直就是大材小用。

 
 
 
  1. import re 
  2.  
  3. def is_in(full_str, sub_str): 
  4.     if re.findall(sub_str, full_str): 
  5.         return True 
  6.     else: 
  7.         return False 
  8.  
  9. print(is_in("hello, python", "llo"))  # True 
  10. print(is_in("hello, python", "lol"))  # False 

【责任编辑:赵宁宁 TEL:(010)68476606】

分享标题:判断字符串是否包含子串,居然有七种方法?
新闻来源:http://www.hantingmc.com/qtweb/news36/118786.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联