对字符串 + 数字句子中的小数点应用十进制格式



我正在尝试对字符串句子中的小数点应用十进制格式 转换为(The temperature of room is 45 degree Celsius)(The temperature of $place is $value degree $unit)

我正在使用python的模板库safe_substitute方法来更改我的字符串参数计量内容。我需要以特定格式({0:.2f})在同一句子中格式化十进制值之一(上一句中的$value)。关于如何做到这一点的任何想法,请回复。

您可以使用

format来控制要在safe_substitute中显示的小数点数,如下所示:

from string import Template
s = Template('(The temperature of $place is $value degree $unit)')
print(s.safe_substitute(place='room', value='{:.2f}'.format(45), unit='Celsius'))

最新更新