Python Count Characters Except Empty Spaces

In Python, a string includes not only the alphanumeric characters and symbols, but also all whitespaces.  Consider this simple example:

>>> mystring = "a b c"
>>> len(mystring)
5
>>>

We have a variable called mystring, and it is assigned to 3 characters a, b, and c.  Note we have separated each character with a space, so when calling the len() function we get the total number of characters along with the whitespaces.

Today we will be discussing how to count only letters in a string in Python.  If you’re up for a challenge, why not try to code it yourself before reading the solutions.  Here’s a link to the Python string methods.  Why not have a read over it and see if anything sparks some coding inspiration?

Method 1: string.count()

Another way of thinking about it is that we can explore how to count whitespace in Python, and from there subtract that from the string. The string method count() is perfect for this!  If you’re not familiar or need a refresher, then read over this article.

Let’s see it in action by passing a space as a parameter.

>>> mystring = "a b c"
>>> mystring.count(" ")
2
>>>

As expected the number of spaces in the mystring variable is 2.  Now let’s subtract the total number of spaces from the total length of mystring.

>>> mystring = "a b c"
>>> len(mystring) - mystring.count(" ")
3
>>>

This is probably the most intuitive way to solve this problem, but let’s check out some more.

Method 2: string.split()

Next, let’s use the Python string method split().  If you specify the parameter as a space (i.e. " "), it will only work for single spaces.

>>> s = "Once upon a time"
>>> s.split(" ")
['Once', 'upon', 'a', 'time']
>>>

When there are consecutive spaces, one space will be considered the delimiter, and the remaining spaces will be empty strings.

>>> s = "Once upon a            time"
>>> s.split(" ")
['Once', 'upon', 'a', '', '', '', '', '', '', '', '', '', '', '', 'time']
>>>

Luckily for us, Python has a way to deal with this.  For the parameter, we either specify the keyword None,

>>> s = "Once upon a            time"
>>> s.split(None)
['Once', 'upon', 'a', 'time']
>>>

or just leave it blank.

>>> s = "Once upon a            time"
>>> s.split()
['Once', 'upon', 'a', 'time']
>>>

The result is a list of words with no spaces.  We now need to calculate the length of each word with len().  A convenient way to handle this is to implement Python’s map() function and apply len() to each element in the list.

>>> map(len, s.split())
<map object at 0x7ff265d52e80>
>>>

Notice the result is a map object, and you can iterate through each result using next().  Below code showing a variable called len_of_each.  It is assigned the results of the map() function.

>>> len_of_each = map(len, s.split())
>>> len_of_each
<map object at 0x7ff265ad7e50>
>>> next(len_of_each)
4
>>> next(len_of_each)
4
>>> next(len_of_each)
1
>>> next(len_of_each)
4
>>>

Let’s pass that variable into the next() function.  Each call will iterate to the next element.  If you need more information regarding map() check out this article.

For our purposes, we will just pass the map object into a list constructor, and then call the sum() function to get our final result.

>>> list(map(len, s.split()))
[4, 4, 1, 4]
>>> sum(list(map(len, s.split())))
13
>>>

Method 3: string.replace()

Lastly, let’s use the replace() method.  We’ll specify to replace each space with an empty string like so:

>>> s = "It was the best of times"
>>> s.replace(" ", "")
'Itwasthebestoftimes'
>>>

This will also work for consecutive spaces.

>>> s = "It         was the best of times"
>>> s.replace(" ", "")
'Itwasthebestoftimes'
>>>

And we just need to call the len() function on it to get the character count.

>>> s = "It         was the best of times"
>>> s.replace(" ", "")
'Itwasthebestoftimes'
>>> len(s.replace(" ", ""))
19
>>>

Summary

Today we explored different ways to count characters in Python except for empty spaces.  For me personally, method 1 was the most intuitive approach.  The problem is solved by first calculating the number of spaces, and then subtracting that from the total length of the string.

len(mystring) - mystring.count(" ")

Secondly, we used split() while either passing the keyword None or without any parameter.  This will account for any consecutive spaces in the string.  The result gave us a list of words.  Python’s map() function is great for calling len() on each of the words in the list.  Don’t forget to pass that into a list() constructor, and then pass that into the sum() function for the character count. 

Here’s a one-liner:

sum(list(map(len, mystring.split())))

Lastly, we implemented the replace() function. This one is a straightforward solution –  we simply specify that we want to replace all spaces with an empty string while passing that into the len() function.

len(mystring.replace(" ", ""))

Hopefully, you tried to solve this on your own before reading through the whole article.  How did your solution compare to mine?