Python 字符串 count() 方法及示例

Python count() 方法

count() 是 Python 的内置函数。它将返回字符串中给定元素的总计数。计数从字符串的开头到结尾开始。也可以指定要开始搜索的起始和结束索引。

Python 字符串 Count() 语法

Python count 函数语法

string.count(char or substring, start, end)

Python 语法参数

  • 字符或子字符串:您可以指定要搜索的单个字符或子字符串。它将返回您在给定字符串中找到的字符或子字符串的计数。
  • start:(可选) 它指示搜索开始的起始索引。如果未给出,则从 0 开始。例如,您想从字符串中间搜索一个字符。您可以为 count 函数提供 start 值。
  • end:(可选) 它指示搜索结束的结束索引。如果未给出,它将搜索列表或给定字符串的末尾。例如,您不想扫描整个字符串,而是希望搜索限制在特定点,您可以在 count 函数中提供 end 值,count 将负责搜索到该点。

返回值

count() 方法将返回一个整数值,即给定字符串中给定元素的计数。如果字符串中找不到该值,则返回 0。

示例 1:字符串上的 Count 方法

以下示例显示了 count() 函数在字符串上的工作方式。

str1 = "Hello World"
str_count1 = str1.count('o')  # counting the character “o” in the givenstring
print("The count of 'o' is", str_count1)

str_count2 = str1.count('o', 0,5)
print("The count of 'o' usingstart/end is", str_count2)

输出

The count of 'o' is 2
The count of 'o' usingstart/end is 1

示例 2:计算给定字符串中某个字符的出现次数

以下示例展示了在给定字符串中以及通过使用 start/end 索引来计算字符的出现次数。

str1 = "Welcome to Guru99 Tutorials!"
str_count1 = str1.count('u')  # counting the character “u” in the given string
print("The count of 'u' is", str_count1)

str_count2 = str1.count('u', 6,15)
print("The count of 'u' usingstart/end is", str_count2)

输出

The count of 'u' is 3
The count of 'u' usingstart/end is 2

示例 3:计算给定字符串中子字符串的出现次数

以下示例展示了在给定字符串中以及通过使用 start/end 索引来计算子字符串的出现次数。

str1 = "Welcome to Guru99 - Free Training Tutorials and Videos for IT Courses"
str_count1 = str1.count('to') # counting the substring “to” in the givenstring
print("The count of 'to' is", str_count1)
str_count2 = str1.count('to', 6,15)
print("The count of 'to' usingstart/end is", str_count2)

输出

The count of 'to' is 2
The count of 'to' usingstart/end is 1

摘要

  • count() 是 Python 的内置函数。它将返回列表或字符串中给定元素的计数。
  • 对于字符串,计数从字符串的开头到结尾开始。也可以指定要开始搜索的起始和结束索引。
  • count() 方法返回一个整数值。