Field Width and Alignment
默认左对齐
'hey {:10}'.format('hello') |
Specify width (Aign left, fill with spaces) |
---|---|
'{:010}'.format(2) |
Fill with zeroesOutput: 0000000002 |
'{:*^30}'.format('text') |
Specify width, align to centerOutput: *************text************* |
Option Meaning, padding '<'
Forces the field to be left-aligned within the available space (this is the default for most objects). '>'
Forces the field to be right-aligned within the available space (this is the default for numbers). '='
Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width. '^'
Forces the field to be centered within the available space.
Member and Element Access
'{0}, {1}, {2}'.format(1, 2, 3) |
Access arguments by ordinal positionOutput: 1, 2, 3 |
---|---|
'{}, {}, {}'.format(1, 2, 3) |
Implicit positional arguments (2.7 and above only)Output: 1, 2, 3 |
'{value1}, {value2}, {value2}'.format(value1=1, value2=2, value3=3) |
Access keyword arguments by nameOutput: 1, 2, 2 |
'{[1]}'.format(['first', 'second', 'third']) |
Access element by indexOutput: second |
'{.name}'.format(sys.stdin) |
Access element attributeOutput: <stdin> |
'{[name]}'.format({'name': 'something'}) |
Access element by keyOutput: something |
Numerical Representation
'{:x}'.format(100) |
Hexadecimal representationOutput: 64 |
---|---|
'{:X}'.format(3487) |
Hexadecimal representation (uppercase letters)Output: D9F |
'{:#x}'.format(100) |
Hexadecimal representation (including the 0x )Output: 0x64 |
'{:b}'.format(100) |
Binary representationOutput: 1100100 |
'{:c}'.format(100) |
Character representationOutput: d |
'{:d}'.format(100) |
Decimal representation (default)Output: 100 |
'{:,}'.format(1000000) |
With thousands separatorOutput: 1,000,000 |
'{:o}'.format(100) |
Octal representationOutput: 144 |
'{:n}'.format(100) |
Like d , but uses locale information for separatorsOutput: 100 |
'{:e}'.format(0.0000000001) |
Exponent notationOutput: 1.000000e-10 |
'{:E}'.format(0.0000000001) |
Exponent notation (capital ‘E’)Output: 1.000000E-10 |
'{:f}'.format(3/14.0) |
Fixed pointOutput: 0.214286 |
'{:g}'.format(3/14.0) |
General formatOutput: 0.214286 |
'{:%}'.format(0.66) |
PercentageOutput: 66.000000% |
'{:.3}'.format(0.214286) |
PrecisionOutput: 0.214 |
Integers
Type Meaning 'b'
Binary format. Outputs the number in base 2. 'c'
Character. Converts the integer to the corresponding unicode character before printing. 'd'
Decimal Integer. Outputs the number in base 10. 'o'
Octal format. Outputs the number in base 8. 'x'
Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. 'X'
Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. 'n'
Number. This is the same as 'd'
, except that it uses the current locale setting to insert the appropriate number separator characters.None The same as 'd'
.
Floating numbers
Type Meaning 'e'
Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is 6
.'E'
Exponent notation. Same as 'e'
except it uses an upper case ‘E’ as the separator character.'f'
Fixed-point notation. Displays the number as a fixed-point number. The default precision is 6
.'F'
Fixed-point notation. Same as 'f'
, but convertsnan
toNAN
andinf
toINF
.'g'
General format. For a given precision p >= 1
, this rounds the number top
significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.The precise rules are as follows: suppose that the result formatted with presentation type'e'
and precisionp-1
would have exponentexp
. Then if-4<= exp < p
, the number is formatted with presentation type'f'
and precisionp-1-exp
. Otherwise, the number is formatted with presentation type'e'
and precisionp-1
. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.Positive and negative infinity, positive and negative zero, and nans, are formatted asinf
,-inf
,0
,-0
andnan
respectively, regardless of the precision.A precision of0
is treated as equivalent to a precision of1
. The default precision is6
.'G'
General format. Same as 'g'
except switches to'E'
if the number gets too large. The representations of infinity and NaN are uppercased, too.'n'
Number. This is the same as 'g'
, except that it uses the current locale setting to insert the appropriate number separator characters.'%'
Percentage. Multiplies the number by 100 and displays in fixed ( 'f'
) format, followed by a percent sign.None Similar to 'g'
, except that fixed-point notation, when used, has at least one digit past the decimal point. The default precision is as high as needed to represent the particular value. The overall effect is to match the output ofstr()
as altered by the other format modifiers.
Conversions
'{!r}'.format('string') |
Calling repr on argumentsOutput: 'string' |
---|---|
'{!s}'.format(1.53438987) |
Calling str on argumentsOutput: 1.53438987 |
Number Formattting
The following table shows various ways to format numbers using Python’s str.format(), including examples for both float formatting and integer formatting.
To run examples use print("FORMAT".format(NUMBER));
So to get the output of the first example, you would run: print("{:.2f}".format(3.1415926));
Number | Format | Output | Description |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | 2 decimal places |
3.1415926 | {:+.2f} | +3.14 | 2 decimal places with sign |
-1 | {:+.2f} | -1.00 | 2 decimal places with sign |
2.71828 | {:.0f} | 3 | No decimal places |
5 | {:0>2d} | 05 | Pad number with zeros (left padding, width 2) |
5 | {:x<4d} | 5xxx | Pad number with x’s (right padding, width 4) |
10 | {:x<4d} | 10xx | Pad number with x’s (right padding, width 4) |
1000000 | {:,} | 1,000,000 | Number format with comma separator |
0.25 | {:.2%} | 25.00% | Format percentage |
1000000000 | {:.2e} | 1.00e+09 | Exponent notation |
13 | {:10d} | 13 | Right aligned (default, width 10) |
13 | {:<10d} | 13 | Left aligned (width 10) |
13 | {:^10d} | 13 | Center aligned (width 10) |
Official Examples
1 | # 1) by position: |
Other Examples
Padding and aligning strings
1 | #alight right |
Truncating Long Strings
1 | '%.5s' % ('xylophone',) #注意后面的小数点呀是truncate |
Combining truncating and padding
1 | '%-10.5s' % ('xylophone',) |
Numbers
1 | '%d' % (42,) |
Getitem and Getattr
1 | person = {'first': 'Jean-Luc', 'last': 'Picard'} |
Datetime
1 | from datetime import datetime |