Python count函数详解与用法指南

Python 的 count() 函数用于计算子字符串或某个元素在字符串或序列(如列表、元组)中出现的次数。


1. 在字符串中使用 count()

语法
str.count(sub[, start[, end]])
  • sub: 要查找的子字符串。
  • start: (可选)查找的起始位置。
  • end: (可选)查找的结束位置。
  • 返回值是子字符串在指定范围内出现的次数。
  • 示例
    text = "hello world, hello Python"
    # 计算 "hello" 出现的次数
    print(text.count("hello"))  # 输出: 2
    
    # 指定范围
    print(text.count("hello", 0, 10))  # 输出: 1
    

    2. 在列表中使用 count()

    语法
    list.count(element)
    
  • element: 要统计的元素。
  • 返回值是该元素在列表中出现的次数。
  • 示例
    nums = [1, 2, 3, 4, 2, 2, 5]
    # 计算 2 出现的次数
    print(nums.count(2))  # 输出: 3
    
    # 计算字符串在列表中出现的次数
    words = ["apple", "banana", "apple", "cherry"]
    print(words.count("apple"))  # 输出: 2
    

    3. 在元组中使用 count()

    与列表用法相同,count() 可以计算某个元素在元组中出现的次数。

    示例
    numbers = (1, 2, 3, 2, 2, 4)
    # 计算 2 出现的次数
    print(numbers.count(2))  # 输出: 3
    

    注意事项

    1. 区分大小写count() 在字符串中是区分大小写的。

      text = "Hello hello"
      print(text.count("hello"))  # 输出: 1
      
    2. 子字符串可以重叠
      如果子字符串重叠,count() 会按非重叠的方式统计。

      text = "aaa"
      print(text.count("aa"))  # 输出: 1
      
    3. 范围边界
      当使用 startend 指定范围时,统计的范围为 [start, end),不包括 end 位置。

      text = "hello world"
      print(text.count("o", 5, 10))  # 输出: 1
      

    作者:阳来了

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python count函数详解与用法指南

    发表回复