【问题标题】:Formatted string with calculated values in Python在 Python 中具有计算值的格式化字符串
【发布时间】:2021-08-12 03:01:43
【问题描述】:

在 JavaScript 中,我可以使用模板文字并包含计算值。例如:

var a = 3;
var b = 8;
var text = `Adding ${a} + ${b} = ${a+b}`;   //  Adding 3 + 8 = 11

我知道 python 有 f'…' 字符串和 str.format() 占位符。有没有办法可以在字符串中包含计算?

【问题讨论】:

  • 只需f'{a} + {b} = {a + b}' 就可以了——基本上就像a,"+",b,"=",a+b
  • f-strings 支持嵌入式计算。你尝试了什么?

标签: python string f-string


【解决方案1】:

使用f-string

a = 3
b = 8    
text = f'{a} + {b} = {a + b}'

本例中的text 变量是一个包含'3 + 8 = 11' 的字符串。

使用str.format

a = 3
b = 8
text = '{0} {1} = {2}'.format(a, b, a + b)

【讨论】:

  • 是的,这行得通。这可以使用str.format()吗?
  • @Manngo 是的,有可能,请参考this thread for an example
  • 可能是'{a} + {b} = {a + b}'.format(**{'a': a, 'b': b, 'a + b': a + b})。但这在很大程度上是一堆重复的标记。只需使用 f 字符串。
  • str.format docs开始,它可以是*args**kwargs,所以使用位置参数不那么冗长(为简单起见)
  • 因此,答案似乎是.format() 方法{…} 中的表达式严格来说是一个键,而不是一个评估表达式。另一方面,在 f-string 中,它被评估。
【解决方案2】:

使用str.format

a = 3
b = 8    
text = '{0} + {1} = {2}'.format(a,b,a+b)
print(text)

使用f-string

f'{a} + {b} = {a + b}'

他们都做同样的事情:

a,"+",b,"=",a+b

【讨论】:

  • .format 的标记已更改,与 OP 问题的意图不同(它们应作为名称提供)。请参阅this thread 了解应该做的事情(即传入一系列关键字)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
相关资源
最近更新 更多