In python, I remember there is a function to do this.
.count?
"The big brown fox is brown" brown = 2.
Count Number of Occurrences in a String with .count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method. In the example above you used the built-in string .
Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.
Method #2: Using Count() function in python: First, we split the string by spaces and store in list. We use count() to find count of that word in list.
Iterate the entire string for that particular character and then increase the counter when we encounter the particular character. Using count() is the most conventional method in Python to get the occurrence of any element in any container. This is easy to code and remember and hence quite popular.
why not read the docs first, it's very simple:
>>> "The big brown fox is brown".count("brown")
2
One thing worth learning if you're a Python beginner is how to use interactive mode to help with this. The first thing to learn is the dir
function which will tell you the attributes of an 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, in Python, methods are also attributes. So now he use the help
function to inquire 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.
This displays the docstring of the method - some help text which you should get in to the habit of putting in your own methods too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With