How to count the number of times when something happens inside a certain row?

In python, I remember that there is a function for this.

.count?

"Big brown fox brown" brown = 2.

+7
python
source share
2 answers

why not read the docs first, it's very simple:

>>> "The big brown fox is brown".count("brown") 2 
+26
source share

One thing worth exploring if you're a Python novice is to use interactive mode to help with this. The first thing to know is the dir function , which will tell you the attributes of the object.

 >>> 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'] 

Remember that in Python, methods are also attributes. So, now he uses the help function to find out about one of the methods that looks promising:

 >>> 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. 

The docstring of the method is displayed here - some help text that you should get used to using your own methods.

+18
source share

All Articles