Format function in python to format output

The format function is a formatting function in python, which can format numbers or strings. Use {} to specify the corresponding parameters. It can accept an unlimited number of parameters, and the positions can be out of order. In {}, you can specify the character string at the corresponding position of the index output.
The syntax format is as follows: {<parameter number>:<format control tag>}, format control tags include: <padding>, <alignment>, <width>, <precision>, <type> and other fields, which are optional Yes, it can be used in combination. Filling is often used together with alignment. ^, <,> are centered, left-aligned, right-aligned, respectively, with a width at the back.: The character with padding at the back can only be one character. If not specified, the default is Use blank padding. One of the {} corresponds to a parameter . If you format the number, you can add d or not add d to {}.

The return value of the format function is str string type , so sometimes we can format the corresponding string through the format function and then write the formatting result of the format function to the file.

if __name__ == '__main__':
    print("我叫{}, 今年{}岁".format("xiaoming", 26))
    # 在{}中指定索引的时候那么就会输出对应索引的字符串
    print("{0} {1} {0}".format("hi", "hello", "hi"))

Format the number (refer to the rookie tutorial):

digital format Output Remarks
2.1342183  {: .2f}  2.13  Keep two decimal places
2.1342183  {: +. 2f}  +2.13  Signed to keep two decimal places
-1  {: +. 2f}  -1.00 Signed to keep two decimal places
2.76271  {:.0f}  3  Without decimals
{:0>2d}  07  The number is filled with 0, starting from the left, and the width is 2
7  {:o<3d}  7th  Number complement o, fill right, width is 3
20  {: x ^ 6d}  xx20xx  Number complement x, aligned in the center
2832828382  {:,}  2,832,828,382 Add a thousands separator for every three digits
0.25  {:.2%}   25.00%  Percentage format
1000000000  {: .2e} 1.002+09 Index representation

The test code is as follows:

if __name__ == '__main__':
    n = 2.1342183
    print("{:.2f}".format(n))

    n = 2.1342183
    print("{:+.2f}".format(n))

    n = -1
    print("{:+.2f}".format(n))

    n = 2.76271
    print("{:.0f}".format(n))

    n = 7
    print("{:0>2}".format(n))

    n = 7
    print("{:o<3}".format(n))

    n = 20
    print("{:x^6d}".format(n))

    n = 2832828382
    print("{:,}".format(n))

    n = 0.25
    print("{:.0%}".format(n))

    n = 1000000000
    print("{:.2e}".format(n))

 

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/115054550