1

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
depperm
  • 10,606
  • 4
  • 43
  • 67
jr17420975320
  • 13
  • 1
  • 4

4 Answers4

4

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())
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

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'
Cleb
  • 25,102
  • 20
  • 116
  • 151
1

A shorter version of @CoryKramer answer:

def get_num_of_non_WS_characters(s):
    return sum(not c.isspace() for c in s)
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
0

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.

  • `str.isspace()` doesn't just check for " ". – kindall Oct 31 '17 at 19:29
  • That will only count the number of chars that aren't equal to the space char, it doesn't exclude other whitespace from the count, like tabs, newlines, etc. – PM 2Ring Oct 31 '17 at 19:29