开发者

4种python判断字符串是否包含关键字的方法

开发者 https://www.devze.com 2025-04-10 09:22 出处:网络 作者: alden_ygq
目录方法 1:使用 in 关键字(最简洁)方法 2:使用 str.find() 方法方法 3:使用 str.index() 方法方法 4:正则表达式(复杂匹配)扩展场景1. 检查多个关键字是否存在2. 统计关键字出现的次数知识扩展总结方法 1:使
目录
  • 方法 1:使用 in 关键字(最简洁)
  • 方法 2:使用 str.find() 方法
  • 方法 3:使用 str.index() 方法
  • 方法 4:正则表达式(复杂匹配)
  • 扩展场景
    • 1. 检查多个关键字是否存在
    • 2. 统计关键字出现的次数
  • 知识扩展
    • 总结

      方法 1:使用 in 关键字(最简洁)

      直接通过 in 操作符检查子字符串是否存在:

      text = "Hello, welcome to python world."
      keyword = "Python"
       
      if keyword in text:
          print(f"包含关键字 '{keyword}'")
      else:
          print(f"不包含关键字 '{keyword}'")
      

      方法 2:使用 str.find() 方法

      find() 返回子字符串的起始GzUtt索引(未找到则返回 -1):

      text = "Hello, welcome to Python world."
      keyword = "Python"
       
      if text.find(keyword) != -1:
          print("关键字存在")
      else:
          print("关键字不存在")
      

      方法 3:使用 str.index() 方法

      与 find() 类似,但未找到时会抛出 ValueError 异常:

      try:
      编程    index = text.index(keyword)
          print(f"关键字在索引 {index} 处")
      except ValueError:
          print("关键字不存在")
      

      方法 4:正则表达式(复杂匹配)

      使用 re 模块实现更灵活的匹配(如忽略大小写、模糊匹配等):

      import re
       
      text = "Hello, welcome to Python world."
      pattern = r"python"  # 正则表达式模式
       
      if re.search(pattern, text, re.IGNORECASE):  # 忽略大小写
          print("关键字存在")
      else:
          print("关键字不存在")
      

      扩展场景

      1. 检查多个关键字是否存在

      使用 any() 结合生成器表达式:

      keywords = ["Pythonandroid", "Java", "C++"]
      text = "I love Python programming."
       
      if any(k in text for k in keywords):
          print("至少包含一个关键字")
      

      2. 统计关键字出现的次数

      使用 str.count():

      count = text.count("Python")
      print(f"关键字出现了 {count} 次")
      

      知识扩展

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

      我们经常会遇这样一个需求:判断字符串中是否包含某个关键词,也就是特定的子字符串。比如从一堆书籍名称中找出含有“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 就说明子串存在于字符串中。

      dandroidef 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

      总结

      推荐使用 in 操作符:简单高效,适用于大多数场景。

      正则表达式:适合需要模糊匹配(如大小写不敏感、模式匹配)的场景。

      避免冗余代码:优先选择直接判断逻辑(如 if keyword in text)。

      到此这篇关于4种pyjavascriptthon判断字符串是否包含关键字的方法的文章就介绍到这了,更多相关python判断字符串是否含关键字内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

      0

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      关注公众号