2009-11-03 13 views
7

पायथन में, मुझे याद है कि ऐसा करने के लिए एक कार्य है।किसी निश्चित स्ट्रिंग के अंदर कुछ बार कितनी गिनती है?

। गणना?

"बड़ी भूरी लोमड़ी भूरा होता है" भूरे रंग = 2.

+0

आपने इस "गिनती" फ़ंक्शन को खोजने और खोजने के लिए कहां खोजा? कौन सा लाइब्रेरी संदर्भ वेबसाइट? कौन सा ट्यूटोरियल वेबसाइट? –

उत्तर

26

क्यों डॉक्स पहले पढ़ा नहीं है, यह बहुत सरल है:

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

सरल अभी तक सुरुचिपूर्ण! – AutomatedTester

18

एक बात सीखने लायक अगर आप एक अजगर शुरुआत कर रहे हैं इस के साथ मदद करने के लिए 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'] 

याद रखें, पायथन में, विधियां भी विशेषताएं हैं। तो अब वह 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

संबंधित मुद्दे