Python中的count()函數是Python的一個內置字符串操作函數,其作用是統計一個字符串中某個字符或子字符串出現的次數。
Python中的count()函數接受一個字符或子字符串作為參數,并返回該字符或子字符串在原字符串指定范圍內出現的次數。
count()函數的語法格式如下:
string_name.count(string, start_index, end_index)
該函數有3個參數,其含義如下:
下面使用幾個例子來介紹該函數的具體使用方法:
例子1:
str1 = "武林網VEVB"
cnt = str1.count("IT")
print(cnt)
輸出:1
即 str1 字符串中有 1 個“IT”子字符串。
例子2:
str1 = "武林網VEVB"
cnt = str1.count("Python")
print(cnt)
輸出:0
即str1字符串中有 0 個子字符串“Python”.
例子3:
str1 = "武林網VEVB"
cnt = str1.count("it")
print(cnt)
輸出:0
從這個例子中可以看出,Python中字符串處理函數count()對字符串是區分大小寫的。
以上3個例子在Python 3.8.2 IDLE中的運行情況如下圖所示:
例子4:
str1 = "武林網VEVB"
str2 = "IT"
cnt = str1.count(str2, 3)
print(cnt)
輸出:1
即從str1位置3開始搜索(也就是從字符I開始搜索),能找到1個子字符串。
例子5:
str1 = "武林網VEVB"
str2 = "IT"
cnt = str1.count(str2, 4)
print(cnt)
輸出:0
從索引位置4開始搜索(即字符“T”開始搜索),沒有找到匹配的子字符串。
以上兩例在Python 3.8.2 IDLE中執行的情況如下圖所示:
例子6:
str1 = "武林網VEVB"
str2 = "IT"
cnt = str1.count(str2, 3, 5)
print(cnt)
輸出:1
從索引位置3開始搜索,搜索到索引位置5,可以找到1個子字符串。
例子7:
str1 = "武林網VEVB"
cnt = str1.count("IT", 3, 4)
print(cnt)
輸出:0
從索引位置3開始(字符“I”),搜索到索引位置4(即字符“T”),結果為0.
要注意的是:end_index是搜索停止位置的索引,所以搜索范圍不會包括end_index處的字符。
以上兩例在Python3.8.2 IDLE中的執行情況如下圖所示:
后面兩個參數,即start_index和end_index可以取負值,取負值時是從后往前數所在的索引位置,如-1,這里指的是從最后一個字符位置,-2是從后面第2個字符位置,以此類推。
(1)start_index為負的情況
例子8:
str1 = "武林網VEVB"
cnt = str1.count("IT", -4)
print(cnt)
輸出:1
這里,start_index的取值為-4,即從后往前數第4個字符作為搜索的起始位置(是字符“I”),可以找到1個子字符串。
例子9:
str1 = "武林網VEVB"
cnt = str1.count("IT",-10)
print(cnt)
輸出:1
這里,start_index參數的值為-10,但str1只有7個字符,這時可以認為Python處理時是從0開始的。
以上兩例在Python 3.8.2 IDLE中執行的情況如下圖所示:
(2)end_index參數為負的情況
例子10:
str1 = "武林網VEVB"
cnt = str1.count("IT", 3, -2)
print(cnt)
輸出:1
此例是從索引位置3(即字符“I”)開始,搜索停止索引位置-2(即字符“樂”)。
例子11:
str1 = "武林網VEVB"
cnt = str1.count("IT", 3, -3)
print(cnt)
輸出:0
從索引位置 3(即字符“I”)開始,搜索停止索引位置 -3 (即字符“T”),沒有找到子字符串。
例子12:
str1 = "武林網VEVB"
cnt = str1.count("IT", -4, -2)
print(cnt)
輸出:1
從后往前數第4個字符“I”開始,搜索停止的位置是從后往前數第2個字符“樂”,找到1個子字符串。
以上3例在Python3.8.2 IDLE中執行的情況如下圖所示:
下面這個例子中使用到了casefold()函數,把字符串中的字母都變為小寫,所以兩次統計的結果是不同的。
str_doc = "I love You.I love everything.Love is the eternal truth in the world."
search_word = "love"
word_cnt1 = str_doc.count(search_word)
word_cnt2 = str_doc.casefold().count(search_word)
print(word_cnt1)
print(word_cnt2)
輸出:
2
3
新聞熱點
疑難解答