[Python] F-string not formatting floats into an integer

Discussão em 'Python' iniciado por Stack, Julho 30, 2025.

  1. Stack

    Stack Membro Participativo

    Usually, I use % string formatting. But, as I discovered f-string is the new way of string formatting and it is faster as well, I want to use it.
    But, I am facing a problem when formatting a float into an integer using f-string. Following is what I have tried:
    Using % string formatting

    '%5d'%1223 # yields --> ' 1223'
    '%5d'%1223.555 # yields --> ' 1223'


    Using f-string formatting

    f'{1223:5d}' # yields --> ' 1223' ==> correct
    f'{1223.555:5d}' # gives error
    # error is "ValueError: Unknown format code 'd' for object of type 'float'"


    Am I missing something?

    Continue reading...

Compartilhe esta Página