python編程語言的內置函數中的count()函數,該函數返回給定字符串中子字符串出現的次數。
用法:
string.count(substring, start=…, end=…)
參數:
- count()函數具有一個強製性參數和兩個可選參數。
強製參數:
1)substring-要查找其計數的字符串。 - 可選參數:
1)start(可選)-搜索開始的字符串中的起始索引。 2)end(可選)-搜索結束的字符串中的結束索引。
返回值:
count()方法返回一個整數,該整數表示在給定字符串中子字符串出現的次數。
以下是count()方法的Python實現,其中沒有可選參數:
# 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"))
輸出:
2
以下是使用可選參數的count()方法的Python實現。
# 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
注:本文由純淨天空篩選整理自Striver大神的英文原創作品 Python String | count()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。