How to check whether a str(variable) is empty or not?

user1275670 picture user1275670 · Mar 29, 2012 · Viewed 379.5k times · Source

How do I make a:

if str(variable) == [contains text]:

condition?

(or something, because I am pretty sure that what I just wrote is completely wrong)

I am sort of trying to check if a random.choice from my list is ["",] (blank) or contains ["text",].

Answer

alexis picture alexis · Mar 29, 2012

You could just compare your string to the empty string:

if variable != "":
    etc.

But you can abbreviate that as follows:

if variable:
    etc.

Explanation: An if actually works by computing a value for the logical expression you give it: True or False. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.