我写了一个函数,如果传递的val
只有空格,例如' '
,它们都被删除,我们返回np.Nan
或null
值。
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(''))
函数按预期返回。输出为:
5
WHAJS
nan
nan
但是现在当我使用这个函数时,我想检查字符串是否为
- 不只是空白
- 非空
然而,当我检查这个时:
check = check_for_empty_strings('')
if (check):
print('tru')
print(check)
else:
print('dsj')
我得到这个输出
tru
nan
为什么第一个是真的?如果check == NaN,那么if (check)
不应该是False吗?我怎样才能检查我的值不只是空白或NULL。
你可以检查np.nan
:
np.isnan(check)
或者您可以返回None
而不是np.nan
,然后像上面在if条件中所做的那样检查它,因为bool(None)
的计算结果为False
。另一方面,如果计算bool(np.nan)
,则得到的输出结果为True
。
check = check_for_empty_strings('')
if (np.isnan(check)):
print('tru')
print(check)
else:
print('dsj')
这是