views:

330

answers:

5

How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?

a = str(52500)
b = str(5)
lengthDiff = len(a) - len(b)
formatted = '%s/%s' % (' '*lengthDiff + b, a)
# formatted looks like:'     5/52500'
+1  A: 

Not sure exactly what you're after, but this looks close:

>>> n = 50
>>> print "%5d" % n
   50

If you want to be more dynamic, use something like rjust:

>>> big_number = 52500
>>> n = 50
>>> print ("%d" % n).rjust(len(str(52500)))
   50

Or even:

>>> n = 50
>>> width = str(len(str(52500)))
>>> ('%' + width + 'd') % n
'   50'
Harley
+8  A: 

Format operator:

>>> "%10d" % 5
'         5'
>>>

Using * spec, the field length can be an argument:

>>> "%*d" % (10,5)
'         5'
>>>
gimel
This was exactly what I needed.
hekevintran
+1  A: 

See String Formatting Operations:

s = '%5i' % (5,)

You still have to dynamically build your formatting string by including the maximum length:

fmt = '%%%ii' % (len('52500'),)
s = fmt % (5,)
unbeknown
+2  A: 

You can just use the %*d formatter to give a width. int(math.ceil(math.log(x, 10))) will give you the number of digits. The * modifier consumes a number, that number is an integer that means how many spaces to space by. So by doing '%*d' % (width, num)` you can specify the width AND render the number without any further python string manipulation.

Here is a solution using math.log to ascertain the length of the 'outof' number.

import math
num = 5
outof = 52500
formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof)

Another solution involves casting the outof number as a string and using len(), you can do that if you prefer:

num = 5
outof = 52500
formatted = '%*d/%d' % (len(str(outof)), num, outof)
Jerub
len(str(x)) is about twice as fast on my system. It's easier to read too :-)
John Fouhy
Yes but that's assuming you know which side of the equation is the longer one.
Harley
math.ceil(math.log(x, 10)) gives wrong results for powers of 10.
unbeknown
Ah interesting. that's why you shouldn't test on a single value, and test on edge cases.
Jerub
+2  A: 

'%*s/%s' % (len(str(a)), b, a)

Ignacio Vazquez-Abrams