@@ -82,32 +82,50 @@ It is even possible to do inline arithmetic with it:
82
82
# 'Five plus ten is 15 and not 30.'
83
83
```
84
84
85
- ## Formatting digits
85
+ ## Formatting Digits
86
86
87
87
Adding thousands separator
88
88
89
89
``` python
90
90
>> > a = 10000000
91
- >> > " {0 :, }" .format(a)
91
+ >> > f " { a :, } "
92
92
# '10,000,000'
93
93
```
94
94
95
95
Rounding
96
96
97
97
``` python
98
98
>> > a = 3.1415926
99
- >> > " {0 :.2f }" .format(a)
99
+ >> > f " { a :.2f } "
100
100
# '3.14'
101
101
```
102
102
103
103
Showing as Percentage
104
104
105
105
``` python
106
106
>> > a = 0.816562
107
- >> > " {0 :.2% }" .format(a)
107
+ >> > f " { a :.2% } "
108
108
# '81.66%'
109
109
```
110
110
111
+ ### Number formatting table
112
+
113
+ | Number | Format | Output | description |
114
+ | ---------- | ------- | --------- | --------------------------------------------- |
115
+ | 3.1415926 | {:.2f} | 3.14 | Format float 2 decimal places |
116
+ | 3.1415926 | {:+.2f} | +3.14 | Format float 2 decimal places with sign |
117
+ | -1 | {:+.2f} | -1.00 | Format float 2 decimal places with sign |
118
+ | 2.71828 | {:.0f} | 3 | Format float with no decimal places |
119
+ | 4 | {:0>2d} | 04 | Pad number with zeros (left padding, width 2) |
120
+ | 4 | {: x <4d} | 4xxx | Pad number with x’s (right padding, width 4) |
121
+ | 10 | {: x <4d} | 10xx | Pad number with x’s (right padding, width 4) |
122
+ | 1000000 | {:,} | 1,000,000 | Number format with comma separator |
123
+ | 0.35 | {:.2%} | 35.00% | Format percentage |
124
+ | 1000000000 | {:.2e} | 1.00e+09 | Exponent notation |
125
+ | 11 | {:11d} | 11 | Right-aligned (default, width 10) |
126
+ | 11 | {:<11d} | 11 | Left-aligned (width 10) |
127
+ | 11 | {:^11d} | 11 | Center aligned (width 10) |
128
+
111
129
## Template Strings
112
130
113
131
A simpler and less powerful mechanism, but it is recommended when handling strings generated by users. Due to their reduced complexity, template strings are a safer choice.
0 commit comments