2009-11-03 41 views
7

在Python中,我記得有一個功能來做到這一點。如何計算某個字符串內發生的次數?

.count?

「最大的棕色狐狸是棕色的」 棕色= 2

+0

你在哪裏搜索,試圖找到這個「計數」功能?哪個圖書館參考網站?哪個教程網站? – 2009-11-03 12:53:42

回答

26

爲什麼不讀第一的文檔,這是非常簡單的:

>>> "The big brown fox is brown".count("brown") 
2 
+1

簡單而優雅! – AutomatedTester 2009-11-03 11:30:03

18

有一兩件事值得學習,如果你是一個Python初學者是如何使用interactive mode來解決這個問題的。首先要學習的是dir function,它會告訴你一個對象的屬性。

>>> mystring = "The big brown fox is brown" 
>>> dir(mystring) 
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ 
ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__g 
t__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__ 
', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', ' 
__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdi 
git', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lst 
rip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit' 
, 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', ' 
translate', 'upper', 'zfill'] 

請記住,在Python中,方法也是屬性。所以,現在他使用help function來電諮詢,看起來有前途的方法大約一個:

>>> help(mystring.count) 
Help on built-in function count: 

count(...) 
    S.count(sub[, start[, end]]) -> int 

    Return the number of non-overlapping occurrences of substring sub in 
    string S[start:end]. Optional arguments start and end are interpreted 
    as in slice notation. 

這顯示了該方法的docstring - 幫助文本,你應該獲得在投入自己的方法太習慣。

+0

+1我不知道幫助方法!謝謝 – systempuntoout 2010-03-17 11:22:44

相關問題