简体   繁体   English

Python - 在if语句中使用string作为条件

[英]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. 所以我可以使用字符串作为if语句的条件。 Is this possible? 这可能吗?

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 (eg a = "__import__('os').system('rm -Rf /')" ). eval()很难调试,在这里没有任何好处,并且如果允许任意用户输入(例如a = "__import__('os').system('rm -Rf /')" ),则很容易被利用。

You could combine the string "a == " with your input string and eval() it. 您可以将字符串“a ==”与输入字符串和eval()组合在一起。 You should do this carefully, because you are allowing arbitrary code to be executed. 您应该仔细执行此操作,因为您允许执行任意代码。

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. if语句if it is not emptyif字符串将始终为True ,因此在if语句中使用它是没有用的。

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. 因此,尝试传递一些计算为布尔值的实际条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM