是否有可能將if
語句中的字符串解析爲字符串?像將字符串解析爲布爾值?
if "1 > 2":
print "1 is greater than 2"
但一些被解析爲
if 1 > 2:
print "1 is greater than 2"
這可能嗎?這是一個程序嗎?
是否有可能將if
語句中的字符串解析爲字符串?像將字符串解析爲布爾值?
if "1 > 2":
print "1 is greater than 2"
但一些被解析爲
if 1 > 2:
print "1 is greater than 2"
這可能嗎?這是一個程序嗎?
這就是eval
的用途。
if eval("1 > 2"):
print "1 is greater than 2"
不過要注意eval
。它會調用提供給它的任何函數。像os.system('rm -rf /')
:/
如果您只是比較數值,這種方法通常會更安全。
這也可以用於非數字值。
from operator import gt, ge, lt, le, eq, ne
def compare(expression):
parts = expression.split()
if len(parts) != 3:
raise Exception("Can only call this with 'A comparator B', like 1 > 2")
a, comp, b = parts
try:
a, b = float(a), float(b)
except:
raise Exception("Comparison only works for numerical values")
ops = {">": gt, '<': lt, '>=': ge, '<=': le, '==': eq, '!=': ne}
if comp not in ops:
raise Exception("Can only compare with %s" % (", ".join(ops)))
return ops.get(comp)(a, b)
def run_comp(expression):
try:
print("{} -> {}".format(expression, compare(expression)))
except Exception as e:
print str(e)
if __name__ == "__main__":
run_comp("1.0 > 2")
run_comp("2.0 > 2")
run_comp("2 >= 2")
run_comp("2 <= 1")
run_comp("5 == 5.0")
run_comp("5 <= 5.0")
run_comp("5 != 5.0")
run_comp("7 != 5.0")
run_comp("pig > orange")
run_comp("1 ! 2")
run_comp("1 >")
輸出
1.0 > 2 -> False
2.0 > 2 -> False
2 >= 2 -> True
2 <= 1 -> False
5 == 5.0 -> True
5 <= 5.0 -> True
5 != 5.0 -> False
7 != 5.0 -> True
Comparison only works for numerical values
Can only compare with >=, ==, <=, !=, <, >
Can only call this with 'A comparator B', like 1 > 2
你當然可以建立這樣的事情。不過,你需要描述你想要處理的字符串的完整語法。你甚至可以評估任意的Python表達式,但這通常不是處理這種事情的安全方式。 – smarx
理論上你可以寫一些代碼來做到這一點。爲什麼你需要這樣做呢?你是否收到很多字符串輸入? – Harrison
@Harrison我正在寫基於基本的語言,而不是寫一個腳本來解析字符串,我想知道我是否可以傳遞一個字符串並以某種方式進行轉換。 – baranskistad