我想编写一个 Python 字符串,执行时会执行以下操作:
if condition:
consequence
else:
alternative
所以,我尝试了类似的方法:
string = 'if condition: consequence; else: alternative;'
执行方式:
>>> exec(string)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
exec(string)
File "<string>", line 1
if condition: consequence; else: alternative;
^
SyntaxError: invalid syntax
但是正如您所看到的,我收到语法错误。字符串应该如何格式化?
感谢您的帮助!
PS:这个问题不是关于如何计算或执行 Python 字符串(请参阅 How do I execute a string containing Python code in Python? ),而是关于执行 if..then..else 子句所需的格式。
一些背景:
我正在关注 Tom Stuart 的《理解计算》一书。其中一部分是关于理解编程语言的工作原理。因此,他给出了玩具语言“SIMPLE”的实现示例代码。他展示了 Ruby 代码如何将 SIMPLE 转换为 Ruby 代码。不过,我正在尝试用 Python 编写这个,因为这让我更感兴趣。 Ruby 示例是:
def to_ruby
"-> e { if (#{condition.to_ruby}).call(e)" +
" then (#{consequence.to_ruby}).call(e)" +
" else (#{alternative.to_ruby}).call(e)" +
" end }"
end
最佳答案
您可以使用exec
来执行Python语句,包括换行符:
>>> exec("if True:\n print 'abc'\nelse:\n print 'def'")
abc
如果使用 Python 3,则打印时需要括号:
>>> exec("if True:\n print('abc')\nelse:\n print('def')")
abc
关于python - 如何在 Python 中格式化字符串,使其在执行时产生有效的 if .. then .. else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34214905/