Count the number of times a character appears in a string in Python

To count the number of times a character appears in a string in Python (both in upper and lower case):

my_string = "Sunny Universe"
desired_character = "U"

count = 0

for char in my_string:
if char.lower() == desired_character.lower():
count += 1

print(count)

Here, the letter “U” appears twice (in upper and lower case) :

2

Another approach:

my_string = "Sunny Universe"
desired_character = "Uu"

count = 0

for char in my_string:
if char in desired_character:
count += 1

print(count)

The result:

2

Function to do the count

Here is a function to count the number of times a character appears in a string in Python:

def count_character(my_string: str, desired_character: str) -> int:
"""
Function to count the number of times a character appears in a string.

:param my_string: The input string
:param desired_character: The desired character/s that you want to check in the string
:return: The number of times the character/s appears in that string
"
""
count = 0
for char in my_string:
if char in desired_character:
count += 1
return count


example_string = "Sunny Universe"
needed_character = "Uu"
print(
count_character(
my_string=example_string, desired_character=needed_character
)
)

The result:

2

Test the function

To test the “count_character” function using Pytest:

import pytest

# Assuming the count_character function is stored under app.string_operations
from app.string_operations import count_character


@pytest.mark.parametrize(
"input_string, desired_character, expected_output",
[
("Sunny Universe", "Uu", 2),
("Sunny Universe", "U", 1),
("World", "o", 1),
("World", "", 0),
("", "", 0),
(" ", " ", 1),
],
)
def test_count_character(input_string, desired_character, expected_output):
"""
Test the count_character function across different strings

:param input_string: The input string to be tested
:param desired_character: The desired character/s that you seek in the string
:param expected_output: The expected number of times the character/s is found in the string
:return:
"
""
assert (
count_character(input_string, desired_character) == expected_output
)

The result:

============================= test session starts =============================
collecting ... collected 6 items

test_string_operations.py::test_count_character[Sunny Universe-Uu-2] PASSED [ '16%']
test_string_operations.py::test_count_character[Sunny Universe-U-1] PASSED [ '33%']
test_string_operations.py::test_count_character[World-o-1] PASSED [ '50%']
test_string_operations.py::test_count_character[World--0] PASSED [ '66%']
test_string_operations.py::test_count_character[--0] PASSED [ '83%']
test_string_operations.py::test_count_character[ - -1] PASSED ['100%']

============================== 6 passed in '0.02s' ==============================

Additional Exercises

Leave a Comment