To count the number of characters in a string without using the “len()” function:
my_string = "Hello World"
count = 0
for _ in my_string:
count += 1
print(count)
The result:
11
Function to count the number of characters
Here is a function to count the number of characters in a string:
def count_characters(my_string: str) -> int:
"""
Count the number of characters in a string
:param my_string: The string you wish to measure
:return: The number of characters in that string
"""
count = 0
for _ in my_string:
count += 1
return count
example_string = "Hello World"
print(count_characters(example_string))
The result:
11
Add a Pytest test
To test the count_characters function using Pytest:
import pytest
# Assuming the count_characters function is stored under app.string_operations
from app.string_operations import count_characters
@pytest.mark.parametrize(
"input_string, expected_output", [("Hello World", 11), ("12345", 5), ("", 0)]
)
def test_count_characters(input_string, expected_output):
"""
Test the count_characters function across various strings
:param input_string: The input string
:param expected_output: The expected number of characters for that string
"""
assert count_characters(input_string) == expected_output
The result:
============================= test session starts =============================
collecting ... collected 3 items
test_string_operations.py::test_count_characters[Hello World-11] PASSED [ '33%']
test_string_operations.py::test_count_characters[12345-5] PASSED [ '66%']
test_string_operations.py::test_count_characters[-0] PASSED ['100%']
============================== 3 passed in '0.01s' ==============================
Additional Exercises
- Find the Max value in a Python List without using the max function
- Find the Min value in a Python List without using the min function
- How to Reverse a String in Python
- Count the Number of Spaces in a String in Python
- Count Vowels in a String in Python
- Count Consonants in a String in Python
- Count the number of times a character appears in a string in Python
- Find the Middle Item in a Python List