David Metcalfe
David Metcalfe

Reputation: 2431

Why does a string in Python resolve to True?

The title might need some re-wording, but here's my question:

The code below ends up False, and thus prints nothing. Changing to d = 1<10 ends up True.

c = "text"
d = 1>10

if d:
    print c

Simple enough. But now if I change d = "more text" the if statement also prints c. Why?

Upvotes: 0

Views: 645

Answers (6)

Tanveer Alam
Tanveer Alam

Reputation: 5275

Truth Value Testing

The following values are considered false:

  • None

  • False

  • Zero of any numeric type, for example, 0, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

From python docs Truth Value Testing

So '', an empty string, returns False.

Upvotes: 2

jrjc
jrjc

Reputation: 21883

See python doc on Boolean operations

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the __nonzero__() special method for a way to change this.)

Upvotes: 2

Maxime Lorant
Maxime Lorant

Reputation: 36181

The only string considered as a False value is the empty string. It's how the __bool__ operation is defined for strings:

>>> bool('foobar')
True
>>> bool('False')
True
>>> bool('')
False

Upvotes: 3

gravetii
gravetii

Reputation: 9654

1>10 is always false, and thus your code sample doesn't print anything. While the empty string returns False, all other strings are always evaluated to True.

Thus

d = "some string"
if d:
    print c

actually prints c since it has evaluated d to be True

Upvotes: 0

Ant&#243;nio Almeida
Ant&#243;nio Almeida

Reputation: 10127

If d is an empty string, it will return False, otherwise, if the string has content, it will return True.

Upvotes: 1

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

That's how python strings are defined. When you try to evaluate them as a boolean, only the empty string returns False. All other strings return True.

>>> bool('not an empty string')
True
>>> bool('')
False

Upvotes: 7

Related Questions