0

Apologies if this is a repeat question but,

what formatting commands do i need to use if I want a single digit number to be displayed with a zero in front?

i.e. the number '2' would be displayed as '02'.

[But, I do not want any value above 10 to have extra zeros in front]

cheers

user2696225
  • 359
  • 2
  • 7
  • 17

2 Answers2

2

You can use this syntax:

>>> "{:0>2}".format(2)
'02'
>>> "{:0>2}".format(98)
'98'
>>> "{:x>4}".format(2)
'xxx2'

More info: Common string operations

SzieberthAdam
  • 3,999
  • 2
  • 23
  • 31
  • Taking my question further, for my general knowledge and future use, what do I do if i wanted to display 02.00? I tried using "{:0>2.2f}".format(2) but this strips off the leading zero? – user2696225 Nov 14 '13 at 16:16
  • The number after the `>` sets the minimum length of the resulted string. In this case it is 5 not 2. Use `{:0>5.2f}".format(2)`. If that helped please accept my answer. – SzieberthAdam Nov 14 '13 at 16:56
0

Try:

if 0 < num < 10:
    return "0" + str(single_digit)
wioh
  • 11
  • 4