Count the Number of Spaces in a String in Python

To count the number of spaces in a string in Python:

my_string = "Good morning and hello world"

count = 0

for c in my_string:
if c == " ":
count += 1

print(count)

The result:

4

Function to count the number of spaces

Here is a function to count the number of spaces in a string in Python:

def count_spaces_string(my_string: str) -> int:
"""
Count the number of spaces in a string

:param my_string: The actual string
:return: The number of spaces in that string
"
""
count = 0
for c in my_string:
if c == " ":
count += 1
return count


example_string = "Good morning and hello world"
print(count_spaces_string(example_string))

The result:

4

Add a Pytest test

To test the “count_spaces_string” function using Pytest:

import pytest

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


@pytest.mark.parametrize(
"input_string, expected_output",
[("Good morning and hello world", 4), ("Hello", 0), ("", 0)],
)
def test_count_spaces_string(input_string, expected_output):
"""
Test the count_spaces_string function across different strings

:param input_string: The input string to test
:param expected_output: The expected number of spaces in the string tested
"
""
assert count_spaces_string(input_string) == expected_output

The result:

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

test_string_operations.py::test_count_spaces_string[Good morning and hello world-4] PASSED [ '33%']
test_string_operations.py::test_count_spaces_string[Hello-0] PASSED [ '66%']
test_string_operations.py::test_count_spaces_string[-0] PASSED ['100%']

============================== 3 passed in '0.01s' ==============================

Additional Exercises

Leave a Comment