Skip to content Skip to sidebar Skip to footer

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 som

Solution 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'

Post a Comment for "Python Parameterize Formatting"