gpt4 book ai didi

python - 将 python f-string 与格式结合

转载 作者:行者123 更新时间:2023-12-03 22:53:50 25 4
gpt4 key购买 nike

我想使用传递给 format 的变量计算 f 字符串中的数学运算方法。例如,我需要类似的东西:

print(f"{{a}} * 3".format(a=2))

此代码打印:
2 * 3

但我想要的结果是 6。我也不会使用 python eval函数来评估这个字符串。

最佳答案

正如 PEP 498 所述:

The str.format() "expression parser" is not suitable for use when implementing f-strings.



虽然您可以执行以下操作:
name = "John"
age = 30
print(f'My name is {{0}} and I am 5 years older than {age - 5}'.format(name))

您在原始问题中提出的要求是不可行的。

您也可以阅读 this Reddit thread看看为什么这可能是一个坏主意。

关于python - 将 python f-string 与格式结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45739647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com