pythonpython-3.xisspace

Python isspace function


I'm having difficulty with the isspace function. Any idea why my code is wrong and how to fix it?

Here is the problem: Implement the get_num_of_non_WS_characters() function. get_num_of_non_WS_characters() has a string parameter and returns the number of characters in the string, excluding all whitespace.

Here is my code:

def get_num_of_non_WS_characters(s):

    count = 0
    for char in s: 
        if char.isspace():
            count = count + 1  
        return count

Solution

  • You want non whitespace, so you should use not

    def get_num_of_non_WS_characters(s):
        count = 0
        for char in s:
            if not char.isspace():
                count += 1
        return count
    
    >>> get_num_of_non_WS_characters('hello')
    5
    >>> get_num_of_non_WS_characters('hello  ')
    5
    

    For completeness, this could be done more succinctly using a generator expression

    def get_num_of_non_WS_characters(s):
        return sum(1 for char in s if not char.isspace())