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

开发 前端
inin 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中。

1. 使用 in 和 not

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

[[338019]]

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

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

2. 使用 find 方法

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

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

3. 使用 index 方法

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

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

4. 使用 count 方法

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

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

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

5. 通过魔法方法

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

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

示例如下:

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

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

6. 借助 operator

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

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

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

7. 使用正则匹配

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

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

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

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

 

责任编辑:赵宁宁 来源: Python编程时光
相关推荐

2024-07-22 15:42:08

Linux字符串

2024-01-09 16:43:49

Shell脚本开发

2024-10-28 15:33:52

2011-12-16 14:45:36

JavaJSP

2011-05-30 13:37:46

JSP

2021-11-19 10:10:14

手机移动设备网络攻击

2016-09-28 20:05:22

2024-12-20 12:10:19

2010-09-02 10:02:17

PHP

2020-08-01 16:19:13

JavaScript字符串开发

2022-10-27 08:09:33

2024-07-29 08:00:00

2023-04-18 15:57:30

2022-09-30 10:48:12

AR制造业

2009-11-13 16:29:11

ADO.NET连接字符

2021-07-02 10:43:52

IT人才首席信息官人才招聘

2016-12-27 19:19:51

2009-10-29 16:32:24

查看Oracle用户的

2020-10-16 18:35:53

JavaScript字符串正则表达式

2009-12-01 11:33:03

PHP判断字符串的包含
点赞
收藏

51CTO技术栈公众号