python - 将精度作为参数传递给 python 格式

标签 python string python-2.7 string-formatting

我想格式化一个精度为参数的 float

"{0:,.2f}$".format(1000 + 1/float(3))
'1,000.33$'

如何将小数位数 (.2f) 作为参数传递?

仅供引用,我知道我可以使用 round(n,precision) 但是当 precision=0 它打印 0.0 这是不是我想要的。我也可以像 "{0:,."这样连接+ str(precision) + "2f}f".format(n) 但你知道......

最佳答案

您可以嵌套格式字段以动态指定精度:

>>> "{1:,.{0}f}$".format(2, 1000 + 1/float(3))
'1,000.33$'
>>>

来自docs :

A format_spec field can also include nested replacement fields within it. These nested replacement fields can contain only a field name; conversion flags and format specifications are not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.

关于python - 将精度作为参数传递给 python 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28590494/

相关文章:

python - django.db.utils.OperationalError : my_table has no column id error?

python - 当其他应用程序运行时,线程运行速度不够快

C 用另一个替换字符数组中的一个字符

c++ - 当数据包含空格时,如何将制表符分隔文件的内容加载到 C++ 中的二维字符串 vector 中?

python - xlwings 函数查找最后一行数据

python - 有没有办法只从 tkFileDialog 获取文件名?

pythons 'print' 语句不调用 .write() 方法?

python - 长度为 k 的非重叠子串的随机采样

python - 如何查看整个队列内容和自动队列推送

python - 在 python-wordpress-xmlrpc 请求上设置自定义 header