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'
>>> "%10d" % 5
' 5'
>>>
Using *
spec, the field length can be an argument:
>>> "%*d" % (10,5)
' 5'
>>>
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)
'%*s/%s' % (len(str(a)), b, 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,)
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.