You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中exec()的反向操作是什么?如何打印表达式列表的字符串与求值结果?

2. Printing Expressions Alongside Their Evaluated Results

If you want to display both the string form of expressions and their computed results, there are two straightforward approaches depending on how you prefer to define your expressions.

Approach 1: Store expressions as strings

This is the most direct method—save your expressions as strings, loop through them, evaluate each with eval(), and print both the expression and its result:

expressions = [
    "10 + 25 * 2",
    "len('Python is awesome')",
    "round(3.14159 * 2, 2)",
    "max([4, 12, 7, 21]) - min([4, 12, 7, 21])"
]

for expr in expressions:
    result = eval(expr)
    print(f"{expr} = {result}")

Running this will output:

10 + 25 * 2 = 60
len('Python is awesome') = 17
round(3.14159 * 2, 2) = 6.28
max([4, 12, 7, 21]) - min([4, 12, 7, 21]) = 17

Approach 2: Use lambdas to avoid string quotes

If you’d rather write actual Python expressions instead of wrapping them in strings, you can wrap each expression in a lambda and use inspect.getsource() to extract the expression text:

import inspect

def print_expr_with_result(expr_func):
    # Extract the expression from the lambda's source code
    source = inspect.getsource(expr_func).strip()
    # Clean up the lambda wrapper to get just the expression
    expr = source.split(':')[-1].strip()
    # Evaluate and print
    result = expr_func()
    print(f"{expr} = {result}")

# Usage: wrap each expression in a lambda
print_expr_with_result(lambda: 10 + 25 * 2)
print_expr_with_result(lambda: len('Python is awesome'))
print_expr_with_result(lambda: round(3.14159 * 2, 2))
print_expr_with_result(lambda: max([4, 12, 7, 21]) - min([4, 12, 7, 21]))

This gives the same output as the first approach, but you don’t have to quote your expressions. The only tradeoff is the extra lambda wrapper, which is a small price for readability.


内容的提问来源于stack exchange,提问作者user5960761

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:29:12