Skip to content

Commit 04c2e8d

Browse files
committed
Add documentation for string.templatelib.convert()
1 parent 115eaa5 commit 04c2e8d

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

Doc/library/string.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,8 @@ Some simple format string examples::
265265
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
266266
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.
267267

268+
.. _formatstrings-conversion:
269+
268270
The *conversion* field causes a type coercion before formatting. Normally, the
269271
job of formatting a value is done by the :meth:`~object.__format__` method of the value
270272
itself. However, in some cases it is desirable to force a type to be formatted

Doc/library/string.templatelib.rst

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
1-
:mod:`!string.templatelib` --- Templates and interpolations for t-strings
2-
=========================================================================
1+
:mod:`!string.templatelib` --- Support for template string literals
2+
===================================================================
33

44
.. module:: string.templatelib
5-
:synopsis: Support for t-string literals.
5+
:synopsis: Support for template string literals.
66

77
**Source code:** :source:`Lib/string/templatelib.py`
88

99
--------------
1010

11-
1211
.. seealso::
1312

1413
* :ref:`Format strings <f-strings>`
@@ -294,3 +293,21 @@ reassigned.
294293
... print(value, expression, conversion, format_spec)
295294
...
296295
3.0 1 + 2 None .2f
296+
297+
298+
Helper functions
299+
----------------
300+
301+
.. function:: convert(obj, /, conversion)
302+
303+
Applies formatted string literal :ref:`conversion <formatstrings-conversion>`
304+
semantics to the given object *obj*.
305+
This is frequently useful for custom template string processing logic.
306+
307+
Three conversion flags are currently supported:
308+
309+
* ``'!s'`` which calls :func:`str` on the value,
310+
* ``'!r'`` which calls :func:`repr`, and
311+
* ``'!a'`` which calls :func:`ascii`.
312+
313+
If the conversion flag is ``None``, *obj* is returned unchanged.

0 commit comments

Comments
 (0)