0

I wrote a function such that if the passed val only has whitespaces in it for example ' ', they all get removed and we return np.Nan or a nullvalue.

def check_for_empty_spaces(val):
    val = val.rstrip()
    if len(val)<1:
        return np.NaN
    else:
        return val
        
print(len(check_for_empty_strings('WHAJS  ')))
print(check_for_empty_strings('WHAJS'))
print(check_for_empty_strings('  '))
print(check_for_empty_strings(''))    

The function returns as desired. The output is:

5
WHAJS
nan
nan

but now when I use this function, I want to check that the string is

  1. not just whitespaces
  2. not NULL

However, when I check this:

check = check_for_empty_strings('')
if (check):
    print('tru')
    print(check)
else:
    print('dsj')

I get this output

tru
nan

Why is the first one tru? If check == NaN then shouldn't if (check) be False? How else can I check that my value is not just whitespaces or NULL.

x89
  • 2,798
  • 5
  • 46
  • 110

2 Answers2

1

Well you can check for np.nan:

np.isnan(check)

Or you can return None instead of np.nan and then check for it as you have done above in the if condition because bool(None) evaluates to False. If you evaluate bool(np.nan) on the other hand you get the output to be True.

sehan2
  • 1,700
  • 1
  • 10
  • 23
  • Your snippet would not work if I check ```np.isnan('')``` – x89 Oct 21 '21 at 08:42
  • Nah that's not what's required. I specifically want to check if my value is nan or not because I could also be testing with other strings like 'Jhdu ' or 'dsd' – x89 Oct 21 '21 at 08:57
  • @x89 what do you want to tell me with your second to last comment? – sehan2 Oct 21 '21 at 09:43
  • I meant that if I check ```np.isnan('mystringvalue ')``` or something like ```np.isnan('mystringvalue ')==False```, it would throw an error. – x89 Oct 21 '21 at 09:55
1
check = check_for_empty_strings('')
if (np.isnan(check)):
    print('tru')
    print(check)
else:
    print('dsj')

This works

Kirushikesh
  • 578
  • 5
  • 8