How to Count the Characters in Python

0 min read 123 words

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

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

Option 2:

def count_char(s,c):
    return s.lower().count(c.lower())

Option 3:

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

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags