Skip to content

Update string-formatting.md #488

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions docs/cheatsheet/string-formatting.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ Python String Formatting
</base-warning-content>
</base-warning>

We can use the %s format specifier to insert variables into strings:

```python
>>> name = 'Pete'
>>> 'Hello %s' % name
Expand Down Expand Up @@ -150,19 +152,19 @@ Showing as Percentage

| Number | Format | Output | description |
| ---------- | ------- | --------- | --------------------------------------------- |
| 3.1415926 | {:.2f} | 3.14 | Format float 2 decimal places |
| 3.1415926 | {:+.2f} | +3.14 | Format float 2 decimal places with sign |
| -1 | {:+.2f} | -1.00 | Format float 2 decimal places with sign |
| 3.1415926 | {:.2f} | 3.14 | Format float to 2 decimal places |
| 3.1415926 | {:+.2f} | +3.14 | Format float to 2 decimal places with sign |
| -1 | {:+.2f} | -1.00 | Format float to 2 decimal places with sign |
| 2.71828 | {:.0f} | 3 | Format float with no decimal places |
| 4 | {:0>2d} | 04 | Pad number with zeros (left padding, width 2) |
| 4 | {:x<4d} | 4xxx | 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.35 | {:.2%} | 35.00% | Format percentage |
| 1000000000 | {:.2e} | 1.00e+09 | Exponent notation |
| 11 | {:11d} | 11 | Right-aligned (default, width 10) |
| 11 | {:<11d} | 11 | Left-aligned (width 10) |
| 11 | {:^11d} | 11 | Center aligned (width 10) |
| 0.35 | {:.2%} | 35.00% | Format float as percentage |
| 1000000000 | {:.2e} | 1.00e+09 | Format number in exponential notation |
| 11 | {:11d} | 11 | Right-aligned (default, width 11) |
| 11 | {:<11d} | 11 | Left-aligned (width 11) |
| 11 | {:^11d} | 11 | Center aligned (width 11) |

## Template Strings

Expand Down