当前位置: 代码网 > it编程>前端脚本>Python > Python判断字符串是否包含特定子串的7种方法

Python判断字符串是否包含特定子串的7种方法

2025年12月12日 Python 我要评论
我们经常会遇这样一个需求:判断字符串中是否包含某个关键词,也就是特定的子字符串。比如从一堆书籍名称中找出含有“python”的书名。判断两个字符串相等很简单,直接 == 就可以

我们经常会遇这样一个需求:判断字符串中是否包含某个关键词,也就是特定的子字符串。比如从一堆书籍名称中找出含有“python”的书名。

判断两个字符串相等很简单,直接 == 就可以了。其实判断包含子串也非常容易,而且还不止一种方法。下面我们就给大家分享 7 种可以达到此效果的方法:

1、使用 in 和 not in

innot inpython 中是很常用的关键字,我们将它们归类为成员运算符。

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

>>> "llo" in "hello, python"
true
>>>
>>> "lol" in "hello, python"
false

2、使用 find 方法

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

>>> "hello, python".find("llo") != -1
true
>>> "hello, python".find("lol") != -1
false
>>

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

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

5、通过魔法方法

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

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

示例如下;

>>> "hello, python".__contains__("llo")
true
>>>
>>> "hello, python".__contains__("lol")
false
>>>

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

6、借助 operator

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

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

>>> import operator
>>>
>>> operator.contains("hello, python", "llo")
true
>>> operator.contains("hello, python", "lol")
false
>>> 

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

8、知识扩展:获取特定字符与子串的完整方法

在python编程中,字符串处理是基础且高频的操作。本文围绕用户提出的'获取字符串中特定字符'的需求,系统梳理了索引访问、切片操作、find()方法及正则表达式四种核心实现方案。

基础字符串访问方法

索引与切片操作

python字符串支持类似列表的索引访问,可通过整数偏移量直接获取字符或子串:

sample_str = "hello, world! this is a sample string with安hjj in it."

# 单字符访问
print("第一个字符:", sample_str[0])  # 输出: h
print("第五个字符:", sample_str[4])  # 输出: o

# 子串切片(左闭右开)
print("前5个字符:", sample_str[:5])  # 输出: hello
print("第7到12个字符:", sample_str[7:12])  # 输出: world
操作类型语法示例返回值类型边界处理
单字符str[index]str索引越界抛出indexerror
子串切片str[start:end]str超出范围自动截断

查找子串位置

使用find()方法可定位子串首次出现的位置,未找到时返回-1:

target = "安hjj"
index = sample_str.find(target)
if index != -1:
    print(f"找到'{target}',位置在:{index}")
    print("完整子串:", sample_str[index:index+len(target)])
else:
    print(f"未找到'{target}'")

高级模式匹配技术

正则表达式匹配 对于复杂模式匹配(如中文+字母组合),推荐使用re模块:

import re

# 匹配'安'开头后跟3个任意字符
pattern = re.compile(r'安\w{3}')  
match = pattern.search(sample_str)
if match:
    print("正则匹配结果:", match.group())

正则表达式常用元字符说明:

元字符匹配规则
\w匹配字母数字及下划线
{3}前驱元素重复3次
.*匹配任意字符(除换行)

完整实现示例

# filename="string_operations.py"
def main():
    sample_str = "hello, world! this is a sample string with安hjj in it."
    
    # 基础访问
    print("索引访问示例:")
    print("第2字符:", sample_str[1])  # e
    print("6-10字符:", sample_str[6:10])  # , wo
    
    # 子串查找
    print("\n子串查找示例:")
    target = "安hjj"
    pos = sample_str.find(target)
    if pos != -1:
        print(f"找到'{target}'于位置{pos}")
    
    # 正则匹配
    print("\n正则匹配示例:")
    import re
    chinese_pattern = re.compile(r'安[a-za-z0-9]{3}')
    result = chinese_pattern.search(sample_str)
    if result:
        print("匹配到中文+字母组合:", result.group())

if __name__ == "__main__":
    main()

运行该程序将依次演示:

  • 基础索引与切片操作
  • 子串查找与位置定位
  • 正则表达式复杂模式匹配

到此这篇关于python判断字符串是否包含特定子串的7种方法的文章就介绍到这了,更多相关python判断字符串是否包含特定子串内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com