pythonstringnumbersdigits

in python how do I convert a single digit number into a double digits string?


So say I have

a = 5

I want to print it as a string '05'


Solution

  • In python 3.6, the fstring or "formatted string literal" mechanism was introduced.

    f"{a:02}"
    

    is the equivalent of the .format format below, but a little bit more terse.


    python 3 before 3.6 prefers a somewhat more verbose formatting system:

    "{0:0=2d}".format(a)
    

    You can take shortcuts here, the above is probably the most verbose variant. The full documentation is available here: http://docs.python.org/3/library/string.html#string-formatting


    print "%02d"%a is the python 2 variant

    The relevant doc link for python2 is: http://docs.python.org/2/library/string.html#format-specification-mini-language