Formatting a Number as a String

How do you format a number as a string so that it has several spaces before it? I want the shorter number 5 to have enough spaces in front of it so that the plus 5 spaces are the same length as 52500. The procedure is below, 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'
+3
source share
5 answers

Formatting Operator :

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

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

>>> "%*d" % (10,5)
'         5'
>>> 
+8
source

%*d, . int(math.ceil(math.log(x, 10))) . * , , , . , '%*d'% (width, num) `, - python.

, math.log "outof".

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

outof len(), , :

num = 5
outof = 52500
formatted = '%*d/%d' % (len(str(outof)), num, outof)
+2

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

+2

. :

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

, :

fmt = '%%%ii' % (len('52500'),)
s = fmt % (5,)
+1

, , :

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

, - rjust:

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

:

>>> n = 50
>>> width = str(len(str(52500)))
>>> ('%' + width + 'd') % n
'   50'
0
source

Source: https://habr.com/ru/post/1705619/


All Articles