在字符串 + 数字的句子中对小数应用小数格式
Apply decimal formatting for a decimal in a sentence of strings + numbers
我正在尝试对字符串句子中的小数点应用小数点格式
(The temperature of $place is $value degree $unit)
转换为 (The temperature of room is 45 degree Celsius)
我正在使用 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'))
我正在尝试对字符串句子中的小数点应用小数点格式
(The temperature of $place is $value degree $unit)
转换为 (The temperature of room is 45 degree Celsius)
我正在使用 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'))