Python 3.x Python参数化格式

Python 3.x Python参数化格式,python-3.x,formatting,Python 3.x,Formatting,所以我想知道是否有一种方法可以参数化格式化操作符 比如说 >>> '{:.4f}'.format(round(1.23456789, 4)) '1.2346 然而,有没有其他方法可以这样做呢 >>> x = 4 >>> '{:.xf}'.format(round(1.23456789, x)) '1.2346 是的,这可以通过一点字符串连接实现。查看下面的代码: >>> x = 4 >>> string

所以我想知道是否有一种方法可以参数化格式化操作符

比如说

>>> '{:.4f}'.format(round(1.23456789, 4))
'1.2346
然而,有没有其他方法可以这样做呢

>>> x = 4
>>> '{:.xf}'.format(round(1.23456789, x))
'1.2346

是的,这可以通过一点字符串连接实现。查看下面的代码:

>>> x = 4
>>> string = '{:.' + str(x) + 'f}'       # concatenate the string value of x
>>> string                               # you can see that string is the same as '{:.4f}'
'{:.4f}'
>>> string.format(round(1.23456789, x))  # the final result
'1.2346'
>>>
或者,如果希望在不使用额外的
字符串的情况下执行此操作,请执行以下操作:

>>> ('{:.' + str(x) + 'f}').format(round(1.23456789, x)) # wrap the concatenated string in parenthesis
'1.2346'

这回答了你的问题吗?是的,这回答了问题。这是一个如此简单的答案,但我没有考虑过。非常感谢。