In Python, we can easily count how many spaces are in a string using a loop and counting the number of spaces we find in the string.
def countSpaces(string):
count = 0
for char in string:
if char in " ":
count = count + 1
return count
print(countSpaces("Hello World!"))
#Output:
1
When working with strings, it can be useful to know how many spaces appear inside a variable.
In Python, we can easily get the count of spaces in a string looping over each character of the string and seeing if it is a space or not.
Below is a function which will count the number of spaces for you in a string using Python.
def countSpaces(string):
count = 0
for char in string:
if char in " ":
count = count + 1
return count
print(countSpaces("Hello World!"))
print(countSpaces("This is a string with some words."))
print(countSpaces("What's up?"))
#Output:
1
6
1
Hopefully this article has been useful for you to learn how to count the number of vowels in a string using Python.