Search code examples
pythonformattingf-string

print with f-string formatting on float - unable to get how the output is generated


x = 100.1205
y = str(x)[6]

which means y=0

When try to execute below code output is 100.

print ("{:.{}f}".format(x,y))

Can anyone tell how it is giving 100 as output.


Solution

  • First off, let's number the fields: the format string '{:.{}f}' is equivalent to '{0:.{1}f}'.

    The argument at position 1 is y, which equals 0, so this is equivalent to '{0:.0f}' by substitution. That is, it formats the argument at position 0 (i.e. x) as a float, with 0 decimal places.

    So, the result is '100', because that's x to 0 decimal places. You can try this with different values of y to see the results:

    >>> '{:.{}f}'.format(100.1205, 0)
    '100'
    >>> '{:.{}f}'.format(100.1205, 1)
    '100.1'
    >>> '{:.{}f}'.format(100.1205, 2)
    '100.12'
    >>> '{:.{}f}'.format(100.1205, 3)
    '100.121'
    >>> '{:.{}f}'.format(100.1205, 4)
    '100.1205'
    >>> '{:.{}f}'.format(100.1205, 5)
    '100.12050'