In Python, the purpose of formatting a string is achieved by using%. (This is consistent with C language)
where integers and floating-point numbers are formatted, you can specify whether to complement 0 and the number of integers and decimals.
First, introduce a concept of field width.
The width of the format output character is represented in the C-language midfield wide.
For example:
You can insert a number between "%" and a letter to indicate the maximum field width.
The%3d represents the output of 3-bit integers, not enough 3-bit right-justified.
The%9.2f represents a floating-point number with an output field width of 9, where the decimal bit is 2, the integer digit is 6, the decimal point is one, and not enough 9-bit right-aligned. (Note: The number before the decimal point must be greater than the number after the decimal point.) The value before the decimal point specifies the total width of the printed number. If omitted (for example:. 2f), it means that the total width is unrestricted. )
The%8s represents the output of a 8-character string, which is not aligns aligned to 8 characters.
Output of%d:
for in range (0,10): ...: print('%d' %i) ... : 0 123456789
%2d Output: (Field width is 2, right-aligned)
for in range (0,10): ...: print('%2d' % i) ...: 1 2 3 4 5 6 7 8 9
%02d output: (Complement 0)
for in range (0,10): ...: print('%02d' %i) ... : . ..:...: 00010203040506070809
Output from%.2d:
for in range (0,10): ...: print('%.2d' % i) ...:00010203040506070809
Questions about%d,%2d,%02d in the Python string