python - 如何在Python格式函数中应用 "%.02f"?

标签 python string python-3.x floating-point formatting

我是 python 的新手,最近我已经迁移到 Python 3 并且 我正在努力适应 format() 函数。

我想做的是 print() 我创造的温度 在 float 中,像这样:

temperature = [23, 24, 25, 26, 27]
print("Today's temperature is %.02f" % (temperature[0]))

而不是使用 %.02f,我想知道如何 可以改为在 format() 函数中编写 % 百分比。

最佳答案

你必须使用{:.02f}

>>> temperature = [23, 24, 25, 26, 27]
>>> print("Today's temperature is %.02f" % (temperature[0]))
Today's temperature is 23.00
>>> print("Today's temperature is {:.02f}".format(temperature[0]))
Today's temperature is 23.00

更多信息可以在 documentation 中找到.但是请参阅 Format Examples

'%03.2f' can be translated to '{:03.2f}'

关于python - 如何在Python格式函数中应用 "%.02f"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32659685/

相关文章:

python - 使用 SQLAlchemy 时 SAM 构建失败

php - ElasticSearch 映射非可搜索字段

string - 如何在 Rust 中遍历字符串中的字符以匹配单词?

java - StringTemplate:如何检测模板中的变量是否未显式设置?

python - 在 Python 程序中处理大量对象

python - 具有多个匹配项的 Django 查询

python - Tensorflow:针对单个图像中不平衡类的加权稀疏_softmax_cross_entropy

swift - 如何计算 Swift 中字符串中前导空格的数量?

python - 如何在运行时在 Python 中从 stub 文件 (.pyi) 获取类型注释?

python - 为 python Web 应用程序运行 apache 服务器时导入错误