首页 > 解决方案 > Python变量输入到格式字符串

问题描述

我目前在这里有这段代码:

test = 2.432
test_formatted = "{:.2f}".format(test)
print(test_formatted)

输出:

2.43

有没有办法将数字变量插入格式字符串?如:

test = 2.432
te = 2
test_formatted = "{:." + str(te) + "f}".format(test)
print(test_formatted)

谢谢!

标签: pythonpython-3.xrounding

解决方案


像这样:

'{{:.{}f}}'.format(te)
# Result: '{:.2f}'

或者直接用 f 字符串转换数字(Python 3.6 和更新版本):

f'{test:.{te}f}'
# Result: '2.43'

推荐阅读