Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting fixed length with python

Tags:

python

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) 
like image 649
Merlin Avatar asked Feb 28 '11 04:02

Merlin


2 Answers

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
like image 171
Wang Dingwei Avatar answered Oct 28 '22 08:10

Wang Dingwei


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')
like image 27
Cameron Avatar answered Oct 28 '22 09:10

Cameron