Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number as a string

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'
like image 936
hekevintran Avatar asked Dec 14 '22 05:12

hekevintran


2 Answers

Format operator:

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

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

>>> "%*d" % (10,5)
'         5'
>>> 
like image 94
gimel Avatar answered Dec 23 '22 03:12

gimel


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

like image 45
Ignacio Vazquez-Abrams Avatar answered Dec 23 '22 02:12

Ignacio Vazquez-Abrams