问题
So I was wondering if there was a way to parameterize the format operator
For example
>>> '{:.4f}'.format(round(1.23456789, 4))
'1.2346
However, is there anyway to do something like this instead
>>> x = 4
>>> '{:.xf}'.format(round(1.23456789, x))
'1.2346
回答1:
Yes, this is possible with a little bit of string concatenation. Check out the code below:
>>> 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'
>>>
or if you wish to do this without the extra string
variable:
>>> ('{:.' + str(x) + 'f}').format(round(1.23456789, x)) # wrap the concatenated string in parenthesis
'1.2346'
来源:https://stackoverflow.com/questions/60892933/python-parameterize-formatting