简体   繁体   中英

Explaination of this Fancier Output Formatting code of python

What does this code do?

for x in range(1,11):
    print('{0:2d} {1:3d} {2:4d}'.format(x,x**2,x**3))
0: | 1: | 2:  => The position in the arg list from which to get 
                 the value.  The order can be anything you want, and
                 you can repeat values, e.g. '{2:...} {0:...} {1:...} {0:...}' 

2 | 3 | 4     => The minimum width of the field in which to display 
                 the value.  Right justified by default for numbers.


d             => The value must be an integer and it will be displayed in 
                 base 10 format (v. hex, octal, or binary format)

Here's an example:

s = "{2:2d}\n{0:3d}\n{1:4d}".format(2, 4, 6)
print(s)

--output:--
 6
  2
   4

Let's make it simpler:

We have three variables that we want to print them:

>>> x = 1
>>> y = 2
>>> z = 3

We can use format method to have a clean output:

The first number in each brace (before : character), is index of variable in the format function parentheses:

>>> print('{0:2d} {1:3d} {2:4d}'.format(x,y,z))
 1   2    3
>>> print('{2:2d} {1:3d} {0:4d}'.format(x,y,z))
 3   2    1

The second number in braces (the number after : character) is the minimum width of the field in which to display the value. Right justified by default:

>>> print('{2:2d} {1:3d} {0:4d}'.format(x,y,z))
 3   2    1
>>> print('{2:5d} {1:5d} {0:5d}'.format(x,y,z))
    3     2     1
>>> print('{2:10d} {1:10d} {0:10d}'.format(x,y,z))
         3          2          1
>>> 

And the d mean Decimal Integer. Outputs the number in base 10:

>>> print('{2:1f} {1:10f} {0:10d}'.format(x,y,z))
3.000000   2.000000          1
>>> print('{2:1d} {1:10d} {0:10f}'.format(x,y,z))
3          2   1.000000
>>> 

f for float and o for octal and etc.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM