Python isspace function

3.3k Views Asked by At

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
4

There are 4 best solutions below

1
Cory Kramer On BEST ANSWER

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())
0
Cleb On

As an alternative you could also simple do:

def get_num_of_non_WS_characters(s):
    return len(''.join(s.split()))

Then

s = 'i am a string'
get_num_of_non_WS_characters(s)

will return 10

This will also remove tabs and new line characters:

s = 'i am a string\nwith line break'
''.join(s.split())

will give

'iamastringwithlinebreak'
2
Andris Jansons On

I would just use n=s.replace(" " , "") and then len(n). Otherwise I think you should increase the count after the if statement and put a continue inside it.

0
AGN Gazer On

A shorter version of @CoryKramer answer:

def get_num_of_non_WS_characters(s):
    return sum(not c.isspace() for c in s)