-1

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
  • 40,483
  • 12
  • 109
  • 137
Eduard
  • 7,080
  • 5
  • 35
  • 61

4 Answers4

5

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
  • 397,926
  • 29
  • 362
  • 485
1

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
  • 7,894
  • 12
  • 54
  • 134
0

What worked was using ternary:

True if '' else False # False

More verbose than in Javascript, but works.

Eduard
  • 7,080
  • 5
  • 35
  • 61
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
U12-Forward
  • 65,118
  • 12
  • 70
  • 89