0

I have written below code to display a leading zero when the string representation of date has less than two digits?

'{}-{}-{:02d}'.format('6th', 'Jun', '1933')

But it is failing with an error:

ValueError: Unknown format code 'd' for object of type 'str'
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
meallhour
  • 13,921
  • 21
  • 60
  • 117
  • 1
    You might want to take a look at the datetime module. – ddejohn May 16 '22 at 18:38
  • 1
    There seem to be extra quotes in your example code, which makes for invalid Python. Can you please fix it? – ddejohn May 16 '22 at 18:39
  • 1
    Does this answer your question? [How can I fill out a Python string with spaces?](https://stackoverflow.com/questions/5676646/how-can-i-fill-out-a-python-string-with-spaces) Specifically, [this answer](https://stackoverflow.com/a/5676884/843953) – Pranav Hosangadi May 16 '22 at 18:45
  • I see this answer has been flagged as a duplicate but for your specific case you could try `'{:0>4}-{}-{}'.format('6th', 'Jun', '1933')` which will add a leading zero if there are less than 4 characters in the day representation. – Stuart Demmer May 16 '22 at 19:29

1 Answers1

0

str.format doesn't need format codes in most situations. You could simply use:

'{}-{}-{:02}'.format('6th', 'Jun', '1933')
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Jasmijn
  • 9,370
  • 2
  • 29
  • 43