Python basic syntax - formatted output

Python basic grammar

python formatted output

python formatted output in the process, my personal learning process point of view, there are two methods to format the output.

The first is the use of% s% d placeholder for output, the effect is this:

info='life is short '
year =2020
print('%d ,%s you need python '%(year,info))

It is this drop in output effect:

2020,life is short you need python

The second function using a dedicated format output format function, compared to the first, in fact, I prefer the second. But sometimes with the first lot easier, because you can knock some code less.

info='life is short '
year=2020
print('{0:},{1:} you need python'.format(year,info))

It is the first output and effect is the same, but I think this format compared them more range. Specific format () method, there are many optional parameters, as follows:

Identifier effect
Pilot symbols, for the positioning value or string to be formatted
<Filling> For filling a single character
<Alignment> <Left> ^ center right justified
<Width> Specifies the width of the output time slot
<,> When a digital output thousands separator
<Accuracy> Decimal precision floating-point maximum output length or string
<Type> Type Integer: bcdox X float type: e E f%

Among them, the type of line or have the necessary instructions to prevent forgetting. Integer type:

  • b is 2 and c is output in the form of binary coded form unicode output (output corresponding values)

  • d is the decimal form octal output o is output

  • x x is a hexadecimal lowercase lowercase uppercase X X output is uppercase hex output

Which it is used in the form of decimal output d

In the floating-point type:

  • e is the scientific notation E lowercase scientific notation is capitalized

  • non-normal scientific notation f fractional output% is the percentage of output

Which is commonly {f} Also note that the value written in the format of the table top to bottom, can not be skipped.

For chestnut:

a=1.123
b=3.1415926
print('a保留一位小数为{0:.1f},b保留两位小数为{1:.2f}'.format(a,b))

输出: a保留一位小数为1.1,b保留两位小数为3.14

As another chestnut:

a='life is short '
print('{:=^20}'.format(a))
输出: ===life is short ===

This one must pay attention to is that when you join the padding character, be sure to make it clear alignment format, or will be error.

Some basic python syntax I Bowen will not do more introduction, I think those are more basic, and find basic tutorial can learn in a very short period of time, I will pick a little important, some of the syntax error-prone Write down, but also to facilitate future if I can forget query.

Guess you like

Origin www.cnblogs.com/magicdata/p/12179555.html