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'
4
  • 1
    You might want to take a look at the datetime module. Commented May 16, 2022 at 18:38
  • 1
    There seem to be extra quotes in your example code, which makes for invalid Python. Can you please fix it? Commented May 16, 2022 at 18:39
  • 1
    Does this answer your question? How can I fill out a Python string with spaces? Specifically, this answer Commented May 16, 2022 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. Commented May 16, 2022 at 19:29

1 Answer 1

0

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

'{}-{}-{:02}'.format('6th', 'Jun', '1933')
Sign up to request clarification or add additional context in comments.

2 Comments

this is throwing an error IndexError: Replacement index 1 out of range for positional args tuple
Did you remove the list display?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.