python - 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)
谢谢!
解决方案
像这样:
'{{:.{}f}}'.format(te)
# Result: '{:.2f}'
或者直接用 f 字符串转换数字(Python 3.6 和更新版本):
f'{test:.{te}f}'
# Result: '2.43'
推荐阅读
- stack-trace - 如何在使用 retrace.jar 去混淆的 android / R8 堆栈跟踪中读取 lambda?
- sql - PostgreSQL 复合外键“列列表不得包含重复项”
- database - 如何在wordpress中运行代码来处理数据库
- python - 如何将逗号分隔的数字字符串转换为数字?
- python - 如何使用于转义字符串中字符的反斜杠不计数
- javascript - 从数组中提取值的意外行为:所有值都是 2
- graphql - 为 React Admin 3.7 实现 GraphQL 数据提供程序
- asp.net-core - JWT 在 .NET Core Web API 中过期太快
- angular - 是否在延迟加载模块时创建 2 个服务实例
- java - 在 Java 中使用序列化和反序列化时如何处理类更改