Python string true value

if <boolean> : # do this 

boolean must be either True or False.

why

 if "poi": print "yes" 

Output: yes

I did not understand why yes prints, since "poi" is true or False.

+7
python
source share
3 answers

Python will do its best to evaluate the "truth" of an expression when a Boolean value is required from this expression.

The rule for strings is that an empty string is considered False , a non-empty string is considered True . The same rule applies to other containers, so an empty dictionary or list is considered False , a dictionary or list with one or more elements is considered True .

The None object is also considered false.

The numeric value 0 is considered false (although the string value '0' is considered true).

All other expressions are considered True .

Details (including how user-defined types can indicate the truth) can be found here: http://docs.python.org/release/2.5.2/lib/truth.html .

+15
source share

In python, any string except an empty string is True by default

t

 if "MyString": # this will print foo print("foo") if "": # this will NOT print foo print("foo") 
+8
source share

This is where Python is added from the implicit constructor of bool() after if , because everything that follows if should be allowed to be logical. In this context, your code is equivalent

 if bool("poi"): print "yes" 

According to the Python constructor, bool(x) accepts something and solves the truth based on the cases below

  • If x is an integer, only 0 is False everything else is True
  • If x is a float, only 0.0 is False everything else is True`
  • If x is a list, only [] is False everything else True
  • If x is given / dict, only {} is False everything else is True
  • If x is a tuple, only () is False everything else True
  • If x is a string, only "" is False everything else is True . Keep in mind that bool("False") will return to True

Here is the log for the cases 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 
+5
source share

All Articles