Skip to content

Commit 3276df6

Browse files
committed
Add examples
1 parent 9c88178 commit 3276df6

1 file changed

Lines changed: 87 additions & 25 deletions

File tree

concepts/string-formatting/about.md

Lines changed: 87 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -30,39 +30,75 @@ In this example, we insert two variable values in the sentence: one `str` and on
3030
The expressions evaluated can be almost anything.
3131
Some of the (wide range) of possibilities that can be evaluated: `str`, `numbers`, variables, arithmetic expressions, conditional expressions, built-in types, slices, functions, lambdas, comprehensions or **any** objects with either `__str__` or `__repr__` methods defined.
3232

33-
Some examples:
33+
Going from simple to complex:
34+
35+
**Inserting a variable** — the simplest use of a f-string is to place a variable directly into the string.
36+
37+
```python
38+
# Assigning a variable
39+
>>> name = "World"
40+
41+
# Inserting that variable
42+
>>> f'Hello, {name}!'
43+
'Hello, World!'
44+
```
45+
46+
**Expressions inside `{}`** — any valid Python expression can be evaluated inside the braces.
47+
Note that using double quotes inside a single-quoted f-string (or vice versa) avoids the need for escape sequences:
3448

3549
```python
36-
# A dictionary of key:value pairs.
50+
# A dictionary of key:value pairs
3751
>>> waves = {'water': 1, 'light': 3, 'sound': 5}
3852

39-
# Using the name waves in an f-string.
40-
>>> f'"A dict can be represented with f-string: {waves}."'
41-
'"A dict can be represented with f-string: {\'water\': 1, \'light\': 3, \'sound\': 5}."'
53+
# Inserting the whole dict
54+
>>> f'Wave ranks: {waves}'
55+
"Wave ranks: {'water': 1, 'light': 3, 'sound': 5}"
56+
57+
# An expression can be evaluated inline
58+
>>> f"Tenfold the value of 'light' is {waves['light'] * 10}."
59+
"Tenfold the value of 'light' is 30."
60+
61+
# A method call can also be evaluated inline
62+
>>> f'{"hello world!".title()} is a classic greeting.'
63+
'Hello World! is a classic greeting.'
4264

43-
# Here, we pull a value from the dictionary by using the key
44-
>>> f'Tenfold the value of "light" is {waves["light"] * 10}.'
45-
'Tenfold the value of "light" is 30.'
65+
# A f-string can be nested inside another f-string
66+
>>> f"{f'hello world!'.title()} is a classic greeting."
67+
'Hello World! is a classic greeting.'
4668
```
4769

48-
Replacement fields (_the `{}` in the f-string_) support output control mechanisms such as width, alignment, precision.
49-
This is defined by the [format specification mini-language][format-mini-language].
70+
**Output formatting** — the [format specification mini-language][format-mini-language] can be used to control alignment, numeric precision, and much more.
71+
The format specification goes after the value, separated by a `:`.
5072

51-
A more complex example of an `f-string` that includes output control:
73+
```python
74+
# Right-align a value to ten characters, rounding it to 3 decimal places.
75+
>>> value = 1 / 7
76+
>>> f'One seventh is {value:10.3f}.'
77+
'One seventh is 0.143.'
78+
79+
# A format specification can be set using variables as well.
80+
>>> padding = 10
81+
>>> precision = 3
82+
>>> f'One seventh is {value:{padding}.{precision}f}.'
83+
'One seventh is 0.143.'
84+
```
85+
86+
**Putting it all together** — variables, expressions, function calls, and output formatting:
5287

5388
```python
54-
# Assigning variables
5589
>>> precision = 3
56-
>>> verb = "see"
57-
>>> the_end = ['end', 'of', 'transmission']
90+
>>> f"{30e8 * 111_000:6.{precision}e}"
91+
'3.330e+14'
5892

59-
# Reassigning verb to 'meet'.
6093
>>> verb = 'meet'
94+
>>> the_end = ['end', 'of', 'transmission']
95+
>>> f'"Have a {"NICE".lower()} day, I will {verb} you after {30e8 * 111_000:6.{precision}e} light-years."{the_end}'
96+
'"Have a nice day, I will meet you after 3.330e+14 light-years."[\'end\', \'of\', \'transmission\']'
6197

62-
# This example includes a function, an arithmetic expression,
63-
# precision formatting, bracket escaping and object formatting.
64-
>>> f'"Have a {"NICE".lower()} day, I will {verb} you after {30e8 * 111_000:6.{precision}e} light-years."{{{the_end}}}'
65-
'"Have a nice day, I will meet you after 3.330e+14 light-years."{[\'end\', \'of\', \'transmission\']}'
98+
# Did you notice the escaped single-quotes in the previous example?
99+
# Using double quotes instead of single quotes for the f-string means the list's single-quoted strings print cleanly.
100+
>>> f"Have a nice day. {the_end}"
101+
"Have a nice day. ['end', 'of', 'transmission']"
66102
```
67103

68104
There are two main limitations to be aware of.
@@ -106,7 +142,7 @@ The complete formatting specifier pattern is `{[<name>][!<conversion>][:<format_
106142
- `<name>` can be a named placeholder or a number or empty.
107143
- `!<conversion>` is optional and should be one of this three conversions: `!s` for [`str()`][str-conversion], `!r` for [`repr()`][repr-conversion] or `!a` for [`ascii()`][ascii-conversion].
108144
By default, `str()` is used.
109-
- `:<format_specifier>` is optional and has a lot of options, which are [listed here][format-specifiers].
145+
- `:<format_specifier>` is optional and controls how the value is displayed. More information about possible options can be [found here][format-specifiers].
110146

111147
Example of conversions for a diacritical letter:
112148

@@ -133,13 +169,39 @@ Example of conversions for a diacritical letter:
133169
"She said her name is not Chloe but 'Zoë'."
134170
```
135171

136-
Example of using format specifiers:
172+
Examples of common format specifiers:
137173

138174
```python
139-
# Formats the object at index 0 as a decimal with zero places,
140-
# then as a right-aligned binary number in an 8 character wide field.
141-
>>> "The number {0:d} has a representation in binary: '{0: >8b}'.".format(42)
142-
"The number 42 has a representation in binary: ' 101010'."
175+
# Integer and binary/hex representations of the same number
176+
>>> my_num = 42
177+
>>> f"{my_num} in binary is {my_num:b}. In hex, it is {my_num:x}"
178+
"42 in binary is 101010. In hex, it is 2a"
179+
180+
# Alignment: left (<), right (>), and center (^) using up to ten characters total
181+
>>> f"[{"left":<10}] [{"right":>10}] [{"center":^10}]"
182+
"[left ] [ right] [ center ]"
183+
184+
# Float precision and scientific notation up to three decimal places
185+
>>> pi = 3.141592653589793
186+
>>> f"fixed: {pi:.3} scientific: {pi:.3e}"
187+
"fixed: 3.142 scientific: 3.142e+00"
188+
189+
# Thousands separator and percentage
190+
>>> balance = 1000
191+
>>> rate = 0.0225
192+
>>> f"Balance: ${balance:,.0f} Interest rate: {rate:.1%}"
193+
"Balance: $1,000 Interest rate: 2.2%"
194+
195+
# Putting it all together
196+
>>> items = [("Widget", 1250, 9.991), ("Gadget", 37, 24.503), ("Doohickey", 4, 149.002)]
197+
>>> header = f"{"Item":<12} {"Qty":>6} {"Price":>9}"
198+
>>> print(header)
199+
Item Qty Price
200+
>>> for name, qty, price in items:
201+
... print(f"{name:<12} {qty:>6} {price:>9.2f}")
202+
Widget 1250 9.99
203+
Gadget 37 24.50
204+
Doohickey 4 149.00
143205
```
144206

145207
More examples are shown at the end of [this documentation][summary-string-format].

0 commit comments

Comments
 (0)