計運算元字串在字串中出現的次數
有一種方法可用於計算另一個字串 str.count 中子字串的出現次數。
str.count(sub[, start[, end]])
str.count 返回一個 int,表示另一個字串中子字串 sub 的非重疊出現次數。可選引數 start 和 end 表示搜尋的開始和結束。預設情況下,start = 0 和 end = len(str) 意味著將搜尋整個字串:
>>> s = "She sells seashells by the seashore."
>>> s.count("sh")
2
>>> s.count("se")
3
>>> s.count("sea")
2
>>> s.count("seashells")
1
通過為 start 指定一個不同的值,end 我們可以獲得更加本地化的搜尋和計數,例如,如果 start 等於 13,則呼叫:
>>> s.count("sea", start)
1
相當於:
>>> t = s[start:]
>>> t.count("sea")
1