📜  Python String count() 方法

📅  最后修改于: 2022-05-13 01:55:27.204000             🧑  作者: Mango

Python String count() 方法

Python String count()函数是Python编程语言中的一个内置函数,它返回给定字符串中子字符串的出现次数。

示例 1:不带可选参数的 count() 方法的实现

Python3
# Python program to demonstrate the use of
# count() method without optional parameters 
  
# string in which occurrence will be checked
string = "geeks for geeks" 
  
# counts the number of times substring occurs in 
# the given string and returns an integer
print(string.count("geeks"))


Python3
# Python program to demonstrate the use of
# count() method  using optional parameters
  
# string in which occurrence will be checked
string = "geeks for geeks" 
  
# counts the number of times substring occurs in 
# the given string between index 0 and 5 and returns 
# an integer
print(string.count("geeks", 0, 5))
  
print(string.count("geeks", 0, 15))


输出:

2

示例 2:使用可选参数实现 count() 方法

Python3

# Python program to demonstrate the use of
# count() method  using optional parameters
  
# string in which occurrence will be checked
string = "geeks for geeks" 
  
# counts the number of times substring occurs in 
# the given string between index 0 and 5 and returns 
# an integer
print(string.count("geeks", 0, 5))
  
print(string.count("geeks", 0, 15))

输出:

1
2