Skip to content

Commit caac300

Browse files
committed
chore: digit formatting examples, formatting table
1 parent 1eae4c9 commit caac300

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

.vscode/settings.json

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
"abspath",
1313
"aiter",
1414
"Anyconfig",
15+
"Arham",
1516
"asctime",
1617
"Batmobile",
1718
"Batwowowowoman",
@@ -42,6 +43,7 @@
4243
"fillvalue",
4344
"filterfalse",
4445
"findall",
46+
"flymemory",
4547
"frozenset",
4648
"getattr",
4749
"getattribute",

docs/cheatsheet/string-formatting.md

+22-4
Original file line numberDiff line numberDiff line change
@@ -82,32 +82,50 @@ It is even possible to do inline arithmetic with it:
8282
# 'Five plus ten is 15 and not 30.'
8383
```
8484

85-
## Formatting digits
85+
## Formatting Digits
8686

8787
Adding thousands separator
8888

8989
```python
9090
>>> a = 10000000
91-
>>> "{0:,}".format(a)
91+
>>> f"{a:,}"
9292
# '10,000,000'
9393
```
9494

9595
Rounding
9696

9797
```python
9898
>>> a = 3.1415926
99-
>>> "{0:.2f}".format(a)
99+
>>> f"{a:.2f}"
100100
# '3.14'
101101
```
102102

103103
Showing as Percentage
104104

105105
```python
106106
>>> a = 0.816562
107-
>>> "{0:.2%}".format(a)
107+
>>> f"{a:.2%}"
108108
# '81.66%'
109109
```
110110

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+
111129
## Template Strings
112130

113131
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

Comments
 (0)