Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print an integer with a set number of spaces before it?

C has printf("%Xd", Y);, which just prints the integer X and makes it take Y spaces on the console window.

For example:

printf("%3d", 10);
console: " 10"`

printf("%5d", 5);
console: "    5"

How do I use this in python 3?

like image 325
dor barlev Avatar asked Dec 24 '22 15:12

dor barlev


2 Answers

This print("{0:10d}".format(5)) will print 5 after 9 blanks. For more reference on formatting in python refer this.

like image 102
Siddharth Avatar answered Feb 22 '23 23:02

Siddharth


In general case, we could use string .format():

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

We could also do that with f strings for python >3.6

>>> f"{'left aligned':<30}"
'left aligned                  '
>>> f"{'right aligned':>30}"
'                 right aligned'
>>> f"{'centered':^30}"
'           centered           '
>>> f"{'centered':*^30}"  # use '*' as a fill char
'***********centered***********'
like image 43
Toon Tran Avatar answered Feb 23 '23 00:02

Toon Tran