user2351418
user2351418

Reputation: 401

Python - Using string as condition in if statement

I am trying to do this:

a = "1 or 0"
if (a): Print "true"

So I can use a string as the condition of an if statement. Is this possible?

Upvotes: 5

Views: 12088

Answers (3)

Blender
Blender

Reputation: 298146

It's possible, but don't do it:

a = '1 or 0'

if eval(a):
    print 'a is True'

eval() is hard to debug, offers no benefit here and is easily exploitable if you allow arbitrary user input (e.g. a = "__import__('os').system('rm -Rf /')").

Upvotes: 11

Amit Yadav
Amit Yadav

Reputation: 1861

A string will always be True for the if statement if it is not empty, so it is of no use to use it in the if statement.

In [12]: my_str = 'a=a'

In [13]: if my_str:
   ....:     print True
   ....: else:
   ....:     print False
   ....:     
True

In [14]: new_str = ''

In [15]: if new_str:
   ....:     print True
   ....: else:
   ....:     print False
   ....:     
False

In [16]: 

So Try to pass some real condition that computes to be a boolean.

Upvotes: 1

Jason Sperske
Jason Sperske

Reputation: 30416

You could combine the string "a == " with your input string and eval() it. You should do this carefully, because you are allowing arbitrary code to be executed.

Upvotes: 3

Related Questions