Python Parameterize Formatting

爷,独闯天下 提交于 2020-12-10 08:11:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!