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

Viewed 21823

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?

6 Answers

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***********'

You can just use the C-like printf in python3:

Your C printf:

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

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

In Python3 is:

print("%3d" % (10));
console: " 10"`

print("%5d" %  (5));
console: "    5"

So to use the C-like printf in Python3, put a "%" instead of a ",".
After that, you just need to use a tuple for the arguments.

A more general case (I get a debug trace from one of my programs):

print("Router: %-5s, subnetToDest: %-20s with hop: %-20s" % (r, s[0], s[1]))
Router: r0   , subnetToDest: 100.30.0.0/16        with hop: Local  

PD, the - in the last example means right alignment.

Related