Setting fixed length with python

24,356

Solution 1

Since you are manipulating strings, str.zfill() does exactly what you want.

>>> s1, s2 = '60', '100'
>>> print s1.zfill(5), s2.zfill(5)
00060 00100

Solution 2

Like this:

num = 60 
formatted_num = u'%05d' % num

See the docs for more information about formatting numbers as strings.

If your number is already a string (as your updated question indicates), you can pad it with zeros to the right width using the rjust string method:

num = u'60'
formatted_num = num.rjust(5, u'0')

Solution 3

If "60" is already a string, you have to convert it to a number before applying the formatting. The most practical one works just like C's printf:

a  ="60"
b = "%05d" % int(a)
Share:
24,356
Merlin
Author by

Merlin

its all about me, status = 200 MLabs!

Updated on July 20, 2022

Comments

  • Merlin
    Merlin almost 2 years

    I have str that are like '60' or '100'. I need the str to be '00060' and '00100',

    How can i do this? code is something like this: I was using '0'+'0'+'0' as plug. now need to fix d==0006000100

      a4 ='60'
      a5 ='100'
    
      d=('0'+'0'+'0'+a4+'0'+'0'+a5) 
    
  • Merlin
    Merlin about 13 years
    it comes as '60' i am combining example 0006000100,
  • Cameron
    Cameron about 13 years
    @user: OK, it seems like Wang's answer (using zfill) is the way to go in your case since it's built for exactly the type of thing you're doing
  • Lauritz V. Thaulow
    Lauritz V. Thaulow about 13 years
    From docs.python.org/release/3.0.1/whatsnew/3.0.html: "the % operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.". Use "".format() instead for future compatibility: u"{0:0>5d}".format(60) or u"{0:0>5s}".format(str(60)).
  • Lauritz V. Thaulow
    Lauritz V. Thaulow about 13 years
    I just discovered you can use !s in the format string to force string conversion, so you need only a single case to handle both 60 and '60': "{0!s:0>5s}".format(60)