0

In Javascript, there is == operator to test if a value is falsy:

'' == false // true

In Python, == corresponds to === in Javascript, which is an exact equation (value & type).

So how to find out if a value is Falsy in Python?

vaultah
  • 44,105
  • 12
  • 114
  • 143
Eduard
  • 8,437
  • 10
  • 42
  • 64

4 Answers4

6

You can obtain the truthiness of a value, by using the bool(..) function:

>>> bool('')
False
>>> bool('foo')
True
>>> bool(1)
True
>>> bool(None)
False

In an if statement, the truthiness is calculated implicitly. You can use the not keyword, to invert the truthiness. For example:

>>> not ''
True
>>> not 'foo'
False
>>> not 1
False
>>> not None
True
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

To get implicit conversion you can just use not - or (for "truthy") just use the variable in place:

if not None:
    print('None')

if not False:
    print('False')

if not '':
    print('empty string')

if not 0:
    print('zero')

if not {}:
    print('empty/zero length container')

if 'hello':
    print('non empty string, truthy test')
paul23
  • 8,799
  • 12
  • 66
  • 149
0

What worked was using ternary:

True if '' else False # False

More verbose than in Javascript, but works.

Eduard
  • 8,437
  • 10
  • 42
  • 64
0

Even tho this question is old, but there is a not not (kinda hacky), but this is the faster than bool(..) and probably the fastest that's possible, you can do it by:

print(not not '')
print(not not 0)
print(not not 'bar')

Output:

False
False
True
U13-Forward
  • 69,221
  • 14
  • 89
  • 114