The format method of Python string type formatting

Python string formatting generally uses the format() method, and the usage is as follows:

<template string>.format(<comma separated parameter>)

Wherein the template string can consist of one or more of the {} composed of grooves , the default numbers start with 0, and assigns numbers to be in the tank, a plurality of the same ID may be specified to repeatedly output the same parameters, for example:

>>>"{}:计算机{}的CPU占用率为{}%".format("2018-4-23", "A", 5)
'2018-4-23:计算机A的CPU占用率为5%'

>>>"{1}:计算机{0}的CPU占用率为{2}%".format("A", "2018-4-23", 5)
'2018-4-23:计算机A的CPU占用率为5%'

>>>"{0}二手车直卖网,买卖{1},就看{0}价".format("瓜子", "二手车")
'瓜子二手车直卖网,买卖二手车,就看瓜子价'

In addition, the formatting method can be configured inside the slot in the .format() method. The configuration method is:

{<parameter serial number>:<format control tag>}

The format control marks are:

<fill> <align> <width> <,> <.Accuracy> <type>
Single character used for padding <Left Alignment
> Right Alignment
^ Center Alignment
Set output width Output with thousands separator Maximum output length. Decimal precision Integer type b, c, d, o, x, X
floating point type e, Ef,%

Some examples of formatted output;

>>>"{:=^20}".format("python")
'=======python======='

>>>"{:10}".format("python")
'python    '

>>>"{:,7.2f}".format(12345.6789)
'12,345.68''

>>>"{0:e},{0:E},{0:f},{0:%}".format(3.14)
'3.140000e+00,3.140000E+00,3.140000,314.000000%'

Guess you like

Origin blog.csdn.net/zzh2910/article/details/80056513