1. 程式人生 > >Python之eval和exec

Python之eval和exec

不能 error: ror character file clas col 相同 rac

eval可以執行字符串形式的表達式

In [1]: eval("1 + 2 + 3")
Out[1]: 6

In [2]: eval("a + 1", {"a": 99})
Out[2]: 100

exec執行字符串形式的代碼

In [3]: exec("print(‘hello world‘)")
hello world

In [4]: exec("print(“hello world“)")
  File "<string>", line 1
    print(“hello world“)
               ^
SyntaxError: invalid character 
in identifier

內外層雙引號不能相同,否則會報錯

Python之eval和exec