Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Parameterize Formatting

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
like image 370
T. Smith Avatar asked Aug 25 '26 02:08

T. Smith


1 Answers

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'
like image 68
Noah Broyles Avatar answered Aug 26 '26 23:08

Noah Broyles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!