Question #6840   Submitted by Answiki on 10/04/2022 at 01:37:07 PM UTC

In Python, how to count the number of occurrences of a character in a string without using the count function?

Answer   Submitted by Answiki on 10/04/2022 at 01:41:28 PM UTC

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.

3 events in history
Answer by Answiki on 10/04/2022 at 01:41:28 PM

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.

Question by Answiki 10/04/2022 at 01:37:15 PM
In Python, how to count the number of occurrences of a character in a string without using the count() function?
Question by Answiki 10/04/2022 at 01:37:07 PM
In Python, how to count the number of occurrences of a character in a string without using the count function?
# ID Query URL Count

Icons proudly provided by Friconix.