0

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?

Satish Thorat
  • 584
  • 1
  • 5
  • 13

1 Answers1

2

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}'
911
  • 542
  • 2
  • 12