From 5828e9bd3154740f0c6629856b9d8ffd0f9021eb Mon Sep 17 00:00:00 2001 From: kovan Date: Tue, 3 Feb 2026 23:15:26 +0100 Subject: [PATCH 1/2] gh-72798: Add mapping example to str.translate documentation Add an example showing how to use str.translate with a dictionary mapping directly, demonstrating character replacement and deletion. Co-Authored-By: Claude Opus 4.5 --- Doc/library/stdtypes.rst | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 0f20163e69509c..8d46f68beff1f3 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -2846,6 +2846,12 @@ expression support in the :mod:`re` module). You can use :meth:`str.maketrans` to create a translation map from character-to-character mappings in different formats. + The following example uses a mapping to replace ``'a'`` with ``'X'``, + ``'b'`` with ``'Y'``, and delete ``'c'``:: + + >>> 'abc123'.translate({ord('a'): 'X', ord('b'): 'Y', ord('c'): None}) + 'XY123' + See also the :mod:`codecs` module for a more flexible approach to custom character mappings. From 4328d06072dfe0fe959a44cdcfe0a04346ff3d12 Mon Sep 17 00:00:00 2001 From: kovan Date: Mon, 9 Feb 2026 18:23:17 +0100 Subject: [PATCH 2/2] gh-72798: Use .. doctest:: directive for str.translate example Co-Authored-By: Claude Opus 4.6 --- Doc/library/stdtypes.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 8d46f68beff1f3..6c552d27762990 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -2847,7 +2847,9 @@ expression support in the :mod:`re` module). character-to-character mappings in different formats. The following example uses a mapping to replace ``'a'`` with ``'X'``, - ``'b'`` with ``'Y'``, and delete ``'c'``:: + ``'b'`` with ``'Y'``, and delete ``'c'``: + + .. doctest:: >>> 'abc123'.translate({ord('a'): 'X', ord('b'): 'Y', ord('c'): None}) 'XY123'