count()是Python中的内置函数。 它返回字符串中给定元素的总数。 从字符串的开始到结束的字符个数。 也可以指定开始和结束索引进行计数。
string.count(char or substring, start, end)
返回
count()方法将返回一个整数值,即来自给定字符串的给定元素的计数。 如果在给定的字符串中找不到该值,则返回0。
示例1:
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)
Output:
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)
Output:
The count of 'to' is 2
The count of 'to' usingstart/end is 1