Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truth value of a string in python

Tags:

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.

like image 700
navyad Avatar asked Aug 28 '13 15:08

navyad


People also ask

What is truth value in Python?

Truthy values are values that evaluate to True in a boolean context. Falsy values are values that evaluate to False in a boolean context. Falsy values include empty sequences (lists, tuples, strings, dictionaries, sets), zero in every numeric type, None , and False .

How do you find the truth value in Python?

We can use any object to test the truth value. By providing the condition in the if or while statement, the checking can be done. Until a class method __bool__() returns False or __len__() method returns 0, we can consider the truth value of that object is True.

Is a string true in Python?

Any string is True , except empty strings. Any number is True , except 0 . Any list, tuple, set, and dictionary are True , except empty ones.

Is 0 true or false in Python?

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.


2 Answers

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.

like image 156
Larry Lustig Avatar answered Oct 02 '22 19:10

Larry Lustig


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")
like image 34
Cameron Sparr Avatar answered Oct 02 '22 19:10

Cameron Sparr