Skip to content

Commit c79d5a7

Browse files
meatball133BethanyG
authored andcommitted
Started
1 parent 7c2f95a commit c79d5a7

File tree

1 file changed

+38
-49
lines changed

1 file changed

+38
-49
lines changed

concepts/string-formatting/about.md

+38-49
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@
22

33
## String Formatting in Python
44

5+
String formatting is the process of converting values to strings and inserting them into a string template.
56
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_.
78
It can be surprising to find out that there are **four** main ways to perform string formatting in Python - each for a different scenario.
89
Some of this is due to Python's long history and some of it is due to considerations like internationalization or input sanitation.
910
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.
1011

12+
## literal string interpolation: The `f-string`
1113

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.
1717

1818
In this example, we insert two variable values in the sentence: one `str` and one `float`:
1919

@@ -23,8 +23,8 @@ In this example, we insert two variable values in the sentence: one `str` and on
2323
...
2424
# The f-string, using the two values.
2525
# 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.'
2828
```
2929

3030
The expressions evaluated can be almost anything.
@@ -37,16 +37,16 @@ Some examples:
3737
>>> waves = {'water': 1, 'light': 3, 'sound': 5}
3838

3939
# 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}."'
4141
'"A dict can be represented with f-string: {\'water\': 1, \'light\': 3, \'sound\': 5}."'
4242

4343
# 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}.'
4545
'Tenfold the value of "light" is 30.'
4646
```
4747

4848
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].
5050

5151
A more complex example of an `f-string` that includes output control:
5252

@@ -61,24 +61,21 @@ A more complex example of an `f-string` that includes output control:
6161

6262
# This example includes a function, str, a nested f-string, an arithmetic expression,
6363
# 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}}}'
6765
'"Have a nice day, I will meet you after 3.330e+14 light-years."{[\'end\', \'of\', \'transmission\']}'
68-
6966
```
7067

7168
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.
7370

7471
```python
75-
>>> print(f"An empty expression will error: {}")
72+
>>> f"An empty expression will error: {}"
7673
SyntaxError: f-string: empty expression not allowed
7774

7875
>>> 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: {
8077
word # I chose a nice variable
81-
}""")
78+
}"""
8279
SyntaxError: f-string expression part cannot include '#'
8380
```
8481

@@ -92,17 +89,16 @@ Also keep in mind that using expressions inside the `f-string` brackets `{}` is
9289
## The `str.format()` Method
9390

9491
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 `{}`.
9693
For example:
9794

9895
```python
9996
# 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')
10298
'My text: named placeholder and 12.'
10399
```
104100

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.
106102

107103
The complete formatting specifier pattern is `{[<name>][!<conversion>][:<format_specifier>]}`:
108104

@@ -115,25 +111,24 @@ Example of conversions for a diacritical letter:
115111

116112
```python
117113
# 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+
121117

122118
# 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: 'ë'"
125121

126122
...
127123

128124
# 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'"
131127

132-
...
133128

134129
# Fills in the object in the first position.
135130
# 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ë')
137132
"She said her name is not Chloe but 'Zoë'."
138133
```
139134

@@ -142,13 +137,12 @@ Example of using format specifiers:
142137
```python
143138
# Formats the object at index 0 as a decimal with zero places,
144139
# 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'."
147142
```
148143

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

151-
152146
## `%` Formatting, or `printf()` Style Formatting
153147

154148
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
157151
This method has been superseded by both `f-strings` and `str.format()`, which is why the nickname for `%` formatting is _'Old Style'_.
158152
It can be still found in python 2 and/or legacy code.
159153
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_.
162155

163156
```python
164157
# Assigning a variable.
165-
>> name = "Anna-conda"
158+
>>> name = "Anna-conda"
166159

167160
# Building a string using %
168-
>> print("The snake's name is %s." % name)
169-
...
161+
>>> "The snake's name is %s." % name
170162
"The snake's name is Anna-conda."
171163
```
172164

@@ -179,33 +171,30 @@ If you want to add multiple variables to a string, you need to supply a [tuple][
179171
>>> fruit = "grapes"
180172

181173
# 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."
184176
```
185177

186-
187178
## Template Strings
188179

189180
[`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.
190181
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.
191182

192-
193183
```python
194-
>> from string import Template
184+
>>> from string import Template
195185

196-
>>> snake_name = "Anna-Conda"
186+
>>> name = "Anna-Conda"
197187

198188
# 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!")
200190

201191
# Calling .substitute() to replace the placeholder with a value.
202-
>> template_string.substitute(snake_name=name)
192+
>>> template_string.substitute(snake_name=name)
203193
'The snake called `Anna-Conda` has escaped!'
204194
```
205195

206196
More information about `Template` string can be found in the Python [documentation][template-string].
207197

208-
209198
## How Do You Choose which Formatting Method to Use?
210199

211200
With all these options and mini-languages, how do you decide what to reach for when formatting Python strings?

0 commit comments

Comments
 (0)