python string count() 方法用于计算子字符串的非重叠出现次数,即 指定为函数的参数。
还可以通过在函数的参数中指定范围的开始和结束来获取该字符串的特定范围内的子字符串计数。start 和 end 是可选参数,解释为切片表示法。如果子字符串为空,则返回字符之间的空字符串数,即字符串的长度加 1。
在下一节中,我们将了解有关 python string count() 方法的更多详细信息。
语法
python 字符串 count() 方法的语法如下。
str.count(sub, start= 0,end=len(string))
参数
以下是 python 字符串 count() 方法的参数。
- sub − 此参数指定要搜索的子字符串。
- start − 此参数是一个整数值,用于指定搜索的起始索引。第一个字符从 '0' 索引开始。如果未指定 start 值,则默认值为 '0',即第一个索引。
- end − 此参数是一个整数值,用于指定搜索结束的结束索引。如果未指定此值,则默认搜索在最后一个索引处结束。
返回值
python string count() 方法返回给定输入字符串中子字符串的出现次数。
例以子字符串、开始值和结束值为参数的 python 字符串 count() 方法返回指定范围内子字符串的出现次数计数。
在以下示例中,字符串 “Hello!Welcome to qikepu”。然后,将要计数的子字符串指定为 'i'。之后,在字符串上调用 count() 函数,其参数为 3,结束值为 30。
str = "Hello! Welcome to qikepu.";
substr = "i";
print("The number of occurrences of the substring in the input string are: ", str.count(substr, 3, 30))
在执行上述程序时,将生成以下输出 -
例
如果未在函数的参数中指定结束值,则字符串的最后一个索引将被视为默认结束值。
下面是一个在 python string count() 函数的帮助下计算给定字符串中子字符串出现次数的示例。在此程序中,将创建一个字符串,并且还指定了子字符串。然后,在字符串上调用 count() 函数,并将 substring 和 start 值作为其参数。
str = "Hello! Welcome to qikepu.";
substr = "to";
print("The number of occurrences of the substring in the input string are: ", str.count(substr, 21))
以下是执行上述程序得到的输出 -
例
如果未在函数的参数中指定 start 和 end 值,则字符串的第 0 个索引将被视为默认起始值,字符串的最后一个索引被视为默认结束值。
下面是一个在 python string count() 函数的帮助下计算给定字符串中子字符串出现次数的示例。
str = "Hello! Welcome to qikepu.";
substr = "t";
print("The number of occurrences of the substring in the input string are: ", str.count(substr))
通过执行上述程序获得以下输出 -
例
如果未在函数的参数中指定 start 和 end 值,则字符串的第 0 个索引将被视为默认起始值,字符串的最后一个索引被视为默认结束值。如果 sub 字符串为空,则返回字符之间的空字符串数,其中 是字符串的长度加 1。
在下面的 count() 函数示例中,创建了一个字符串并指定了一个空的 sub 字符串。然后,在字符串上调用 count() 函数,而不提供 start 和 end 值。
str = "Hello! Welcome to qikepu.";
substr = "";
print("The number of occurrences of the substring in the input string are: ", str.count(substr))
上述程序在执行时显示以下输出 -
例
子字符串是 python 字符串 count() 方法的必需参数。如果未指定此参数,则会出现类型错误。
下面是一个在 python string count() 函数的帮助下计算输入字符串中子字符串出现次数的示例。 在以下示例中,将创建一个字符串。然后,在字符串上调用 count() 函数,将 start 和 end 值作为其参数,但未指定要计数的子字符串。
str = "Hello! Welcome to qikepu.";
print("The number of occurrences of the substring in the input string are: ", str.count(2, 21))
上述程序的输出显示如下 -
File "main.py", line 2, in
print("The number of occurrences of the substring in the input string are: ", str.count(2, 21))
TypeError: must be str, not int