如何在python中使用'exec()'命​​令

Jak*_*evi 1 python exec

对于以下代码:

command = '\'{:.' + str(3) + 'f}\'.format(' + str(12.6543423) + ')'

print(command)
print('{:.3f}'.format(12.6543423))
print(exec(command))
Run Code Online (Sandbox Code Playgroud)

预期成绩:

'{:.3f}'.format(12.6543423)
12.654
12.654
Run Code Online (Sandbox Code Playgroud)

实际结果:

'{:.3f}'.format(12.6543423)
12.654
None
Run Code Online (Sandbox Code Playgroud)

请有人能告诉我我做错了什么以及如何解决它?我都在尝试编写一个数字舍入函数并尝试理解exec命令.

Ned*_*der 9

或者根本不使用exec或eval.使用功能format提供:

>>> '{:.{}f}'.format(12.6543423, 3)
12.654
Run Code Online (Sandbox Code Playgroud)

  • @JakeLevi了解eval和exec是好的.了解它们最重要的事情之一是它们真的是你几乎从不需要的钝器. (2认同)