Skip to content

Commit eacff55

Browse files
committed
Tweaks to string-formatting concept
1 parent 218e87e commit eacff55

File tree

2 files changed

+27
-21
lines changed

2 files changed

+27
-21
lines changed

concepts/string-formatting/about.md

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ Some examples:
4646
```
4747

4848
Replacement fields (_the `{}` in the f-string_) support output control mechanisms such as width, alignment, precision.
49-
This specification is started in the [format specification mini-language][format-mini-language].
49+
This is defined by the [format specification mini-language][format-mini-language].
5050

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

@@ -59,24 +59,25 @@ A more complex example of an `f-string` that includes output control:
5959
# Reassigning verb to 'meet'.
6060
>>> verb = 'meet'
6161

62-
# This example includes a function, str, a nested f-string, an arithmetic expression,
62+
# This example includes a function, an arithmetic expression,
6363
# precision formatting, bracket escaping and object formatting.
64-
>>> f'"Have a {"NICE".lower()} day, I will {verb} you after {f"{30e8 * 111_000:6.{precision}e}"} light-years."{{{the_end}}}'
64+
>>> f'"Have a {"NICE".lower()} day, I will {verb} you after {30e8 * 111_000:6.{precision}e} light-years."{{{the_end}}}'
6565
'"Have a nice day, I will meet you after 3.330e+14 light-years."{[\'end\', \'of\', \'transmission\']}'
6666
```
6767

68-
There are a few limitations to be aware of.
69-
`f-string` expressions cannot be empty, they cannot contain comments.
68+
There are two main limitations to be aware of.
69+
`f-string` expressions cannot be empty.
70+
[Additionally, before Python 3.12, they cannot contain comments.][pep-0701]
7071

7172
```python
7273
>>> f"An empty expression will error: {}"
7374
SyntaxError: f-string: empty expression not allowed
7475

7576
>>> word = 'word'
76-
>>> f"""A comment in a triple quoted f-string will error: {
77+
>>> f"""A comment in a triple quoted f-string: {
7778
word # I chose a nice variable
7879
}"""
79-
SyntaxError: f-string expression part cannot include '#'
80+
'A comment in a triple quoted f-string: word'
8081
```
8182

8283
~~~~exercism/caution
@@ -105,7 +106,7 @@ The complete formatting specifier pattern is `{[<name>][!<conversion>][:<format_
105106
- `<name>` can be a named placeholder or a number or empty.
106107
- `!<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].
107108
By default, `str()` is used.
108-
- `:<format_specifier>` is optional and has a lot of options, which we are [listed here][format-specifiers].
109+
- `:<format_specifier>` is optional and has a lot of options, which are [listed here][format-specifiers].
109110

110111
Example of conversions for a diacritical letter:
111112

@@ -178,7 +179,9 @@ If you want to add multiple variables to a string, you need to supply a [tuple][
178179
## Template Strings
179180

180181
[`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.
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.
182+
Template strings support `$`-based substitution and are much simpler and less capable than the other options mentioned here.
183+
However, they can be very useful for when complicated internationalization is needed, or outside inputs need to be sanitized.
184+
`string.Template` is considered safer for untrusted user input because it prevents evaluating arbitrary expressions or accessing object attributes, which mitigates format-string injection attacks.
182185

183186
```python
184187
>>> from string import Template
@@ -204,8 +207,8 @@ A few quick guidelines:
204207
If you don't need to internationalize, they should be the Python 3.6+ preferred method.
205208
2. `str.format()` is versatile, very powerful and compatible with both `gnu gettext` and most versions of Python.
206209
3. If simplicity, safety, and/or heavy internationalization is what you need, `string.Template()` can be used to mitigate risks when inputs from users need to be handled, and for wrapping translation strings.
207-
4. The `%` operator is not supported in some newer distributions of Python and should mostly be used for compatibility with old code.
208-
`%` formatting` can lead to issues displaying non-ascii and unicode characters and has more errors and less functionality than other methods.
210+
4. The `%` operator is generally considered deprecated for new code, though it still works in modern Python. It should mostly be used for compatibility with older codebases.
211+
`%` formatting can lead to issues displaying non-ASCII and Unicode characters and has more errors and less functionality than other methods. Check your specific Python distribution for support details if you intend to use it.
209212

210213
If you want to go further: [all about formatting][all-about-formatting] and [Python String Formatting Best Practices][formatting best practices] are good places to start.
211214

@@ -216,6 +219,7 @@ If you want to go further: [all about formatting][all-about-formatting] and [Pyt
216219
[format-specifiers]: https://www.python.org/dev/peps/pep-3101/#standard-format-specifiers
217220
[formatting best practices]: https://realpython.com/python-string-formatting/
218221
[pep-0498]: https://peps.python.org/pep-0498
222+
[pep-0701]: https://peps.python.org/pep-0701/
219223
[printf-style-docs]: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
220224
[repr-conversion]: https://www.w3resource.com/python/built-in-function/repr.php
221225
[str-conversion]: https://www.w3resource.com/python/built-in-function/str.php

concepts/string-formatting/introduction.md

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,20 @@
33
## String Formatting in Python
44

55
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-
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-
Some of this is due to Python's long history and some of it is due to considerations like internationalization or input sanitation.
6+
For Python 3.6+, **literal string interpolation** (**`f-strings`**) is often the obvious and preferred way to format strings:
97

10-
With 4 different paths to take, how do you decide what to use?
8+
```python
9+
>>> adjective = "easy"
10+
>>> f"This is an {adjective} way to format strings!"
11+
'This is an easy way to format strings!'
12+
```
1113

12-
1. `f-strings` are the newest and easiest to read.
13-
If you don't need to internationalize, they should be the Python 3.6+ preferred method.
14-
2. `str.format()` is versatile, very powerful and compatible with both `gnu gettext` and most versions of Python.
15-
3. If simplicity, safety, and/or heavy internationalization is what you need, `string.Template()` can be used to mitigate risks when inputs need to be handled and for wrapping translation strings.
16-
4. The `%` operator should mostly be used for compatibility with old code.
17-
`%` formatting` can lead to issues displaying non-ascii and unicode characters and has more errors and less functionality than other methods.
14+
However, given Python's long history and different considerations, it might not be surprising that there are **three** other common ways to perform string formatting in Python:
15+
16+
1. `str.format()` is versatile, very powerful and compatible with both `gnu gettext` and most versions of Python.
17+
2. If simplicity, safety, and/or heavy internationalization is what you need, `string.Template()` can be used to mitigate risks when inputs need to be handled and for wrapping translation strings.
18+
3. The `%` operator is generally considered deprecated for new code, though it still works in modern Python.
19+
It should mostly be used for compatibility with older codebases. `%` formatting can lead to issues displaying non-ASCII and Unicode characters and has more errors and less functionality than other methods.Check your specific Python distribution for support details if you intend to use it.
1820

1921
If you want to go further: [all about formatting][all-about-formatting] and [Python String Formatting Best Practices][formatting best practices] are good places to start.
2022

0 commit comments

Comments
 (0)