You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: concepts/string-formatting/about.md
+38-49
Original file line number
Diff line number
Diff line change
@@ -2,18 +2,18 @@
2
2
3
3
## String Formatting in Python
4
4
5
+
String formatting is the process of converting values to strings and inserting them into a string template.
5
6
The [Zen of Python][zen-of-python] asserts there should be "one _obvious_ way to do something in Python".
6
-
But when it comes to string formatting, things are a little ...._less zen_.
7
+
But when it comes to string formatting, things are a little ... _less zen_.
7
8
It can be surprising to find out that there are **four** main ways to perform string formatting in Python - each for a different scenario.
8
9
Some of this is due to Python's long history and some of it is due to considerations like internationalization or input sanitation.
9
10
We will start with the most recent additions to the string formatting toolbox and work our way backward to "old style" or "printf() style" string formatting.
10
11
12
+
## literal string interpolation: The `f-string`
11
13
12
-
## literal string interpolation: The `f-string`
13
-
14
-
Introduced in [Python 3.6][pep-0498], [`f-strings`][f-string] (_short for "formatted-strings"_) or [literal string interpolation][string interpolation] are a way of quickly and efficiently evaluating and formatting expressions and strings to a `str` type using the `f` (or `F`) prefix before the brackets (_like so `f'{object}'`_).
15
-
They can be used with all enclosing string types as: single quote `'`, double quote `"` and with multi-lines and escaping triple quotes `'''` or `"""`.
16
-
Any variables, expressions, or other types placed inside the `{}` are first evaluated, then converted to a `str`, then concatenated with any `str` outside the curly braces.
14
+
Introduced in [Python 3.6][pep-0498], [`f-strings`][f-string] (_short for "formatted-strings"_) or [literal string interpolation][string interpolation] are a way of quickly and efficiently evaluating and formatting expressions and strings to a `str` type using the `f` (or `F`) prefix before the brackets (_like so `f'{object}'`_).
15
+
They can be used with all enclosing string types as: single-line `'` or `"` and with multi-lines `'''` or `"""`.
16
+
Any variables, expressions, or other types placed inside the `{}` are first evaluated, then converted to a `str`, then concatenated with any `str` outside the curly braces.
17
17
18
18
In this example, we insert two variable values in the sentence: one `str` and one `float`:
19
19
@@ -23,8 +23,8 @@ In this example, we insert two variable values in the sentence: one `str` and on
23
23
...
24
24
# The f-string, using the two values.
25
25
# The .2f format code truncates so the value displays as 0.12.
26
-
>>>print(f'An {name} is approximately {value:.2f}.')
27
-
'An eighth is approximately 0.12.'
26
+
>>>f'An {name} is approximately {value:.2f}.'
27
+
'An eighth is approximately 0.12.'
28
28
```
29
29
30
30
The expressions evaluated can be almost anything.
@@ -37,16 +37,16 @@ Some examples:
37
37
>>> waves = {'water': 1, 'light': 3, 'sound': 5}
38
38
39
39
# Using the name waves in an f-string.
40
-
>>>print(f'"A dict can be represented with f-string: {waves}."')
40
+
>>>f'"A dict can be represented with f-string: {waves}."'
41
41
'"A dict can be represented with f-string: {\'water\': 1, \'light\': 3, \'sound\': 5}."'
42
42
43
43
# Here, we pull a value from the dictionary by using the key
44
-
>>>print(f'Tenfold the value of "light" is {waves["light"]*10}.')
44
+
>>>f'Tenfold the value of "light" is {waves["light"]*10}.'
45
45
'Tenfold the value of "light" is 30.'
46
46
```
47
47
48
48
Replacement fields (_the `{}` in the f-string_) support output control mechanisms such as width, alignment, precision.
49
-
This is the same [format specification mini-language][format-mini-language] that is used by the `str.format()` method.
49
+
This specification is started in the [format specification mini-language][format-mini-language].
50
50
51
51
A more complex example of an `f-string` that includes output control:
52
52
@@ -61,24 +61,21 @@ A more complex example of an `f-string` that includes output control:
61
61
62
62
# This example includes a function, str, a nested f-string, an arithmetic expression,
63
63
# precision formatting, bracket escaping and object formatting.
64
-
>>> message =f'"Have a {"NICE".lower()} day, I will {verb} you after {f"{30e8*111_000:6.{precision}e}"} light-years."{{{the_end}}}'
65
-
...
66
-
>>>print(message)
64
+
>>>f'"Have a {"NICE".lower()} day, I will {verb} you after {f"{30e8*111_000:6.{precision}e}"} light-years."{{{the_end}}}'
67
65
'"Have a nice day, I will meet you after 3.330e+14 light-years."{[\'end\', \'of\', \'transmission\']}'
68
-
69
66
```
70
67
71
68
There are a few limitations to be aware of.
72
-
`f-string` expressions cannot be empty, they cannot contain comments, and for Python versions earlier than Python 3.7, they cannot contain `await` or `async for` clauses:
69
+
`f-string` expressions cannot be empty, they cannot contain comments.
73
70
74
71
```python
75
-
>>>print(f"An empty expression will error: {}")
72
+
>>>f"An empty expression will error: {}"
76
73
SyntaxError: f-string: empty expression not allowed
77
74
78
75
>>> word ='word'
79
-
>>>print(f"""A comment in a triple quoted f-string will error: {
76
+
>>>f"""A comment in a triple quoted f-string will error: {
80
77
word # I chose a nice variable
81
-
}""")
78
+
}"""
82
79
SyntaxError: f-string expression part cannot include '#'
83
80
```
84
81
@@ -92,17 +89,16 @@ Also keep in mind that using expressions inside the `f-string` brackets `{}` is
92
89
## The `str.format()` Method
93
90
94
91
The [`str.format()`][str-format] method replaces placeholders within the string with values fed as arguments to the function.
95
-
The placeholders are identified with named (`{price}`), numbered (`{0}` or indexed) or even empty (_positional_) placeholders `{}`.
92
+
The placeholders are identified with named (`{price}`), numbered (`{0}` or indexed) or even empty (_positional_) placeholders `{}`.
96
93
For example:
97
94
98
95
```python
99
96
# A named placeholder and a positional placeholder.
100
-
>>>print('My text: {placeholder_1} and {}.'.format(12, placeholder_1='named placeholder'))
101
-
...
97
+
>>>'My text: {placeholder_1} and {}.'.format(12, placeholder_1='named placeholder')
102
98
'My text: named placeholder and 12.'
103
99
```
104
100
105
-
As with `f-strings`, Pythons `str.format()` supports a whole range of [mini language format specifier][format-mini-language] that can be used to align text, convert, etc.
101
+
As with `f-strings`, Pythons `str.format()` supports a whole range of [mini language format specifier][format-mini-language] that can be used to align text, convert, etc.
106
102
107
103
The complete formatting specifier pattern is `{[<name>][!<conversion>][:<format_specifier>]}`:
108
104
@@ -115,25 +111,24 @@ Example of conversions for a diacritical letter:
115
111
116
112
```python
117
113
# Fills in the object at index zero, converted to a string.
118
-
>>>print('An e with an umlaut: {0!s}'.format('ë'))
119
-
An e with an umlaut: ë
120
-
...
114
+
>>>'An e with an umlaut: {0!s}'.format('ë')
115
+
'An e with an umlaut: ë'
116
+
121
117
122
118
# Fills in the object at index zero, converted to a repr.
123
-
>>>print('An e with an umlaut object representation: {0!r}'.format('ë'))
124
-
An e with an umlaut object representation: 'ë'
119
+
>>>'An e with an umlaut object representation: {0!r}'.format('ë')
120
+
"An e with an umlaut object representation: 'ë'"
125
121
126
122
...
127
123
128
124
# Fills in the object at index zero, converted to ascii
129
-
>>>print('An e with an umlaut converted into ascii: {0!a}'.format('ë'))
130
-
An e with an umlaut converted into ascii: '\xeb'
125
+
>>>'An e with an umlaut converted into ascii: {0!a}'.format('ë')
126
+
"An e with an umlaut converted into ascii: '\xeb'"
131
127
132
-
...
133
128
134
129
# Fills in the object in the first position.
135
130
# Then fills in the object in the second position formatted as a repr
136
-
>>>print('She said her name is not {} but {!r}.'.format('Chloe', 'Zoë'))
131
+
>>>'She said her name is not {} but {!r}.'.format('Chloe', 'Zoë')
137
132
"She said her name is not Chloe but 'Zoë'."
138
133
```
139
134
@@ -142,13 +137,12 @@ Example of using format specifiers:
142
137
```python
143
138
# Formats the object at index 0 as a decimal with zero places,
144
139
# then as a right-aligned binary number in an 8 character wide field.
145
-
>>>print("The number {0:d} has a representation in binary: '{0: >8b}'.".format(42))
146
-
The number 42 has a representation in binary: ' 101010'.
140
+
>>>"The number {0:d} has a representation in binary: '{0: >8b}'.".format(42)
141
+
"The number 42 has a representation in binary: ' 101010'."
147
142
```
148
143
149
144
More examples are shown at the end of [this documentation][summary-string-format].
150
145
151
-
152
146
## `%` Formatting, or `printf()` Style Formatting
153
147
154
148
Use of the `%` operator for formatting is the oldest method of string formatting in Python.
@@ -157,16 +151,14 @@ It comes from the C language and allows the use of positional arguments to build
157
151
This method has been superseded by both `f-strings` and `str.format()`, which is why the nickname for `%` formatting is _'Old Style'_.
158
152
It can be still found in python 2 and/or legacy code.
159
153
While using this method will work in Python 3.x, `%` formatting is usually avoided because it can be error-prone, is less efficient, has fewer options available, and any placeholder-argument mismatch can raise an exception.
160
-
Using the `%` operator is similar to [`printf()`][printf-style-docs], so it is also sometimes called _printf formatting_.
161
-
154
+
Using the `%` operator is similar to [`printf()`][printf-style-docs], so it is also sometimes called _printf formatting_.
162
155
163
156
```python
164
157
# Assigning a variable.
165
-
>> name ="Anna-conda"
158
+
>>> name ="Anna-conda"
166
159
167
160
# Building a string using %
168
-
>>print("The snake's name is %s."% name)
169
-
...
161
+
>>>"The snake's name is %s."% name
170
162
"The snake's name is Anna-conda."
171
163
```
172
164
@@ -179,33 +171,30 @@ If you want to add multiple variables to a string, you need to supply a [tuple][
179
171
>>> fruit ="grapes"
180
172
181
173
# Building a string using %
182
-
>>>print("Surprisingly, %ss favorite snack was %s."%(name, fruit))
183
-
Surprisingly, Billy the Kids favorite snack was grapes.
174
+
>>>"Surprisingly, %ss favorite snack was %s."%(name, fruit)
175
+
"Surprisingly, Billy the Kids favorite snack was grapes."
184
176
```
185
177
186
-
187
178
## Template Strings
188
179
189
180
[`string.Template()`][string.Template()] is a class from the `string` module (_as opposed to the built-in `str` type_), which is part of the Python standard library, but has to be imported for use.
190
181
Template strings support `$`-based substitution and are much simpler and less capable than the other options mentioned here, but can be very useful for when complicated internationalization is needed, or outside inputs need to be sanitized.
191
182
192
-
193
183
```python
194
-
>>from string import Template
184
+
>>>from string import Template
195
185
196
-
>>>snake_name="Anna-Conda"
186
+
>>>name="Anna-Conda"
197
187
198
188
# Creating a Template() with placeholder text
199
-
>> template_string = Template("The snake called `$snake_name` has escaped!")
189
+
>>> template_string = Template("The snake called `$snake_name` has escaped!")
200
190
201
191
# Calling .substitute() to replace the placeholder with a value.
202
-
>> template_string.substitute(snake_name=name)
192
+
>>> template_string.substitute(snake_name=name)
203
193
'The snake called `Anna-Conda` has escaped!'
204
194
```
205
195
206
196
More information about `Template` string can be found in the Python [documentation][template-string].
207
197
208
-
209
198
## How Do You Choose which Formatting Method to Use?
210
199
211
200
With all these options and mini-languages, how do you decide what to reach for when formatting Python strings?
0 commit comments