95

So say i have

a = 5

i want to print it as a string '05'

Joe Schmoe
  • 1,815
  • 3
  • 15
  • 14
  • 4
    Please read the tutorial. Particularly on string formatting. After reading that, please update your question. http://docs.python.org/library/stdtypes.html#string-formatting – S.Lott Aug 17 '10 at 18:48

11 Answers11

166

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

jkerian
  • 16,497
  • 3
  • 46
  • 59
  • 1
    The new Python 3 formatting is available in 2.6 as well, 2.7/3 allows you to be a little more terse with positional arguments. – Nick T Aug 17 '10 at 19:03
  • 6
    Simply, `"{:02d}".format(a)` would also work!! If you want 4 digits, simply replace 2 with 4 `"{:04d}".format(a)`. This is for Python3. – nishant Jul 06 '20 at 16:07
  • How do I do 4 digits regardless of its sign (positive or negative)? So if I have -10, it shall be -0010. And 10 will be 0010. – kabison33 Dec 14 '21 at 12:50
28
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.

tux21b
  • 90,183
  • 16
  • 117
  • 101
23
>>> print '{0}'.format('5'.zfill(2))
05

Read more here.

user225312
  • 126,773
  • 69
  • 172
  • 181
9
>>> 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

Mohammad Shahid Siddiqui
  • 3,730
  • 2
  • 27
  • 12
9

In Python 3.6 you can use so called f-strings. In my opinion this method is much clearer to read.

>>> f'{a:02d}'
'05'
Higs
  • 384
  • 2
  • 7
5

In Python3, you can:

print("%02d" % a)
Sarvesh Chitko
  • 158
  • 1
  • 9
5

Based on what @user225312 said, you can use .zfill() to add paddng to numbers converted to strings.

My approach is to leave number as a number until the moment you want to convert it into string:

>>> num = 11
>>> padding = 3
>>> print(str(num).zfill(padding))
011
Jaydeep Mistry
  • 111
  • 2
  • 4
1

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']

1
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
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

If you are an analyst and not a full stack guy, this might be more intuitive:

[(str('00000') + str(i))[-5:] for i in arange(100)]

breaking that down, you:

  • start by creating a list that repeats 0's or X's, in this case, 100 long, i.e., arange(100)

  • add the numbers you want to the string, in this case, numbers 0-99, i.e., 'i'

  • keep only the right hand 5 digits, i.e., '[-5:]' for subsetting

  • output is numbered list, all with 5 digits

chughts
  • 4,210
  • 2
  • 14
  • 27
0

This is a dumb solution but I was getting type errors with the other solutions above. So if all else fails, yolo:

images3digit = []

for i in images:
        if len(i)==1:
            i = '00'+i
            images3digit.append(i)
        elif len(i)==2:
            i = '0'+i
            images3digit.append(i)
        elif len(i)==3:
            images3digit.append(i)
K Puri
  • 21
  • 1