Truth value of a string in python
if <boolean> :
# do this
boolean has to be either True or False.
then why
if "poi":
print "yes"
output: yes
i didn't get why yes is printing , since "poi" is nether True or False.
Python will do its best to evaluate the "truthiness" of an expression when a boolean value is needed from that expression.
The rule for strings is that an empty string is considered False
, a non-empty string is considered True
. The same rule is imposed on other containers, so an empty dictionary or list is considered False
, a dictionary or list with one or more entries is considered True
.
The None
object is also considered false.
A numerical value of 0
is considered false (although a string value of '0'
is considered true).
All other expressions are considered True
.
Details (including how user-defined types can specify truthiness) can be found here: http://docs.python.org/release/2.5.2/lib/truth.html.
In python, any string except an empty string defaults to True
ie,
if "MyString":
# this will print foo
print("foo")
if "":
# this will NOT print foo
print("foo")
What is happening here is Python' supplement of implicit bool()
constructor after the if
, Because anything followed by if
should be resolved to be boolean. In this context your code is equivalent to
if bool("hello"):
print "yes"
According to Python bool(x)
constructor accepts anything and decides the truthiness based on below cases
- If x is integer, Only
0
isFalse
everything else isTrue
- If x is float, Only
0.0
isFalse
everything else is True` - If x is list, Only
[]
isFalse
everything else isTrue
- If x is set/dict, Only
{}
isFalse
everything else isTrue
- If x is tuple, Only
()
isFalse
everything else isTrue
- If x is string, Only
“"
isFalse
everything else isTrue
. Be aware thatbool(“False”)
will return toTrue
Here is the log for the cases I listed above
Python 3.4.3 (default, Feb 25 2015, 21:28:45)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bool(0)
False
>>> bool(1)
True
>>> bool(-1)
True
>>> bool(0.0)
False
>>> bool(0.02)
True
>>> bool(-0.10)
True
>>> bool([])
False
>>> bool([1,2])
True
>>> bool(())
False
>>> bool(("Hello","World"))
True
>>> bool({})
False
>>> bool({1,2,3})
True
>>> bool({1:"One", 2:"Two"})
True
>>> bool("")
False
>>> bool("Hello")
True
>>> bool("False")
True