How to Count the Characters in Python

The challenge

The goal of this challenge is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive.

Examples:

count_char("fizzbuzz","z") # 4 count_char("Fancy fifth fly aloof","f") # 5
Code language: Python (python)

The character can be any alphanumeric character.

The solution in Python code

Option 1:

def count_char(haystack, needle): count = 0 for c in haystack: if c.lower()==needle.lower(): count+=1 return count
Code language: Python (python)

Option 2:

def count_char(s,c): return s.lower().count(c.lower())
Code language: Python (python)

Option 3:

from collections import Counter def count_char(s, c): return Counter(s.lower())[c.lower()]
Code language: Python (python)

Test cases to validate our solution

test.assert_equals(count_char("Hello there", "e"), 3) test.assert_equals(count_char("Hello there", "t"), 1) test.assert_equals(count_char("Hello there", "h"), 2) test.assert_equals(count_char("Hello there", "L"), 2) test.assert_equals(count_char("Hello there", " "), 1)
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments