python - 如何在 Python 中格式化字符串,使其在执行时产生有效的 if .. then .. else 语句?

标签 python string conditional-statements execution

我想编写一个 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/

相关文章:

python - 如何在 Python 中转换对象

javascript - 我可以根据jquery中的条件分配函数吗?

r - 从 dplyr 中以空格分隔的字符串中提取第 n 个位置

python - 如何在 Python 中检测非 ASCII 字符?

mysql - 不同的条件选择不同的语句

c++ - for 循环在满足条件时不会结束

python - Django:启动迁移到 heroku 时没有名为 'psycopg2' 的模块

python - 每隔 n 个位置将列表中的项目插入另一个列表

Python:用字符串替换数值

ruby-on-rails - 测试字符串是否无内容