Setting fixed length using python

I have str that look like "60" or "100". I need str to be "00060" and "00100",

How can i do this? the code looks something like this: I used "0" + "0" + "0" as a fork. now you need to fix d == 0006000100

a4 ='60' a5 ='100' d=('0'+'0'+'0'+a4+'0'+'0'+a5) 
+8
python
Feb 28 2018-11-11T00:
source share
5 answers

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

 >>> s1, s2 = '60', '100' >>> print s1.zfill(5), s2.zfill(5) 00060 00100 
+23
Feb 28 '11 at 4:13
source share

Like this:

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

For more information on formatting numbers as strings, see docs .

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

 num = u'60' formatted_num = num.rjust(5, u'0') 
+10
Feb 28 2018-11-11T00:
source share

If "60" is already a string, you must convert it to a number before applying formatting. The most practical one works the same as C printf:

 a ="60" b = "%05d" % int(a) 
+2
Feb 28 '11 at 4:10
source share

Read your favorite Python documentation:

http://docs.python.org/library/string.html#formatstrings

""

If the zero field precedes the width field ('0'), this allows you to add zero. This is equivalent to the alignment type '=' and the padding character '0'. ""

0
Feb 28 '11 at 4:08
source share

If this is already a string, you can use the .zfill () method.

 myval.fill(5) 
0
Feb 28 '11 at 9:27 a.m.
source share



All Articles