5

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?

4
  • 3
    Yes, but it's strongly discouraged. It would be better to change your code to avoid this. Commented May 5, 2013 at 7:25
  • @Volatility Discouraged by whom? Not by PEP-8 which says "For sequences, (strings, lists, tuples), use the fact that empty sequences are false." Commented May 5, 2013 at 8:23
  • @Anonymous: The string is valid Python code (which I think is intentional), so I think OP is basically asking "can I treat this string as code and evaluate it", which is what eval is for. Commented May 5, 2013 at 8:25
  • 1
    @Anonymous I think you've missed the point of the question. I was talking about having code which means you have to use eval. Commented May 5, 2013 at 8:27

3 Answers 3

11

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 /')").

Sign up to request clarification or add additional context in comments.

2 Comments

I read the question as "if a = 1 or 0" and assumed that they forgot the comparison ==. But your answer makes more sense
3

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.