In Python, how to count the number of occurrences of a character in a string without using the count() function?
In Python, to count the number of occurrences of a character in a string without using the count() function, you have to loop through the string:
# Return the number of occurrences of
# a given character in a string
def countHandMade(string, char):
count = 0
# Loop through the string
for i in string:
if i == char:
count = count + 1
return count
# Example
string ="AnsWiki"
# Display 1
print (countHandMade(string, 'A'))
# Display 2
print (countHandMade(string, 'i'))
Try online on repl.it.
In Python, to count the number of occurrences of a character in a string without using the count() function, you have to loop through the string:
# Return the number of occurrences of
# a given character in a string
def countHandMade(string, char):
count = 0
# Loop through the string
for i in string:
if i == char:
count = count + 1
return count
# Example
string ="AnsWiki"
# Display 1
print (countHandMade(string, 'A'))
# Display 2
print (countHandMade(string, 'i'))
Try online on repl.it.
| # | ID | Query | URL | Count |
|---|---|---|---|---|
| 0 | 11807 | en | https://en.ans.wiki/6841/in-python-how-to-count-the-number-of-occurrences-of-a-character-in-a-string-without-using-the-count-function | 6 |