in python how do I convert a single digit number into a double digits string?
Question
So say i have
a = 5
i want to print it as a string '05'
Solution
print "%02d"%a
is the python 2 variant
python 3 uses a somewhat more verbose formatting system:
"{0:0=2d}".format(a)
The relevant doc link for python2 is: http://docs.python.org/2/library/string.html#format-specification-mini-language
For python3, it's http://docs.python.org/3/library/string.html#string-formatting
OTHER TIPS
a = 5
print '%02d' % a
# output: 05
The '%' operator is called string formatting operator when used with a string on the left side. '%d'
is the formatting code to print out an integer number (you will get a type error if the value isn't numeric). With '%2d
you can specify the length, and '%02d'
can be used to set the padding character to a 0 instead of the default space.
>>> print '{0}'.format('5'.zfill(2))
05
Read more here.
>>> a=["%02d" % x for x in range(24)]
>>> a
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
>>>
It is that simple
In Python3, you can:
print("%02d" % a)
Branching off of Mohommad's answer:
str_years = [x for x in range(24)]
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
#Or, if you're starting with ints:
int_years = [int(x) for x in str_years]
#Formatted here
form_years = ["%02d" % x for x in int_years]
print(form_years)
#['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
df["col_name"].str.rjust(4,'0')#(length of string,'value') --> ValueXXX --> 0XXX
df["col_name"].str.ljust(4,'0')#(length of string,'value') --> XXXValue --> XXX0