Python 字符串 count() 示例

Python 数

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

的语法 Python字符串计数()

Python count 函数语法:

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

参数 Python 句法

  • 字符或子字符串: 您可以指定要在给定字符串中搜索的单个字符或子字符串。它将返回给定字符串中字符或子字符串的数量。
  • 开始 :(可选)表示搜索的起始索引。如果未指定,则从 0 开始。例如,您想从字符串中间搜索一个字符。您可以将起始值提供给 count 函数。
  • end:(可选)它表示搜索结束的结束索引。如果未指定,它将搜索到给定列表或字符串的末尾。例如,如果您不想扫描整个字符串并将搜索限制到特定点,您可以在 count 函数中指定结束值,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:计算给定字符串中某个字符的出现次数

下面的示例通过使用开始/结束索引来显示给定字符串中字符的出现情况。

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:计算给定字符串中子字符串的出现次数

下面的示例显示了给定字符串中子字符串的出现情况以及使用开始/结束索引。

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() 方法返回一个整数值。