bool() or similar

Andrew Dalke dalke at dalkescientific.com
Tue Nov 13 14:16:32 EST 2001


Oliver Fromme:
>However, I wonder if there is a good way to convert some-
>thing to a boolean value (0 or 1), given any type of object?
>Such as a bool() function, which works in the same way as
>int() or str().  I.e. it would return 0 when given either
>0, "", an empty sequence or an empty mapping, and 1 other-
>wise.

>>> for x in (0, 1, 2, (), (1,), ((),), [], ["Q"], "hello", ""):
...     print repr(x), operator.truth(x)
...
0 0
1 1
2 1
() 0
(1,) 1
((),) 1
[] 0
['Q'] 1
'hello' 1
'' 0
>>>

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list