Satish Thorat
Satish Thorat

Reputation: 924

F-string not formatting floats into an integer

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?

Upvotes: 5

Views: 8589

Answers (1)

911
911

Reputation: 691

The reason for this error is that the format specifier d is specifically for formatting integers, not floats.You can use the general format specifier f instead.

f'{int(1223.555):5d}'

Upvotes: 5

Related Questions