Skip to content

Commit 9b8d59c

Browse files
kovanclaude
andauthored
gh-72798: Add mapping example to str.translate documentation (#144454)
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 <noreply@anthropic.com>
1 parent 2c1ca6b commit 9b8d59c

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

Doc/library/stdtypes.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2870,6 +2870,14 @@ expression support in the :mod:`re` module).
28702870
You can use :meth:`str.maketrans` to create a translation map from
28712871
character-to-character mappings in different formats.
28722872

2873+
The following example uses a mapping to replace ``'a'`` with ``'X'``,
2874+
``'b'`` with ``'Y'``, and delete ``'c'``:
2875+
2876+
.. doctest::
2877+
2878+
>>> 'abc123'.translate({ord('a'): 'X', ord('b'): 'Y', ord('c'): None})
2879+
'XY123'
2880+
28732881
See also the :mod:`codecs` module for a more flexible approach to custom
28742882
character mappings.
28752883

0 commit comments

Comments
 (0)