Python Glossary Русский

all Python 3Strings (str)function

str.translate

replacement

Map characters through a translation table (usually from str.maketrans).

Syntax

s.translate(table)

Table keys are character codes from ord, not characters: a dict like {'a': 'A'} raises nothing and silently replaces nothing, which is why the table is nearly always built with str.maketrans. A value of None (or maketrans's third argument) deletes the character, and a replacement may be longer than one character. Unlike a chain of replace calls, the string is walked exactly once and inserted text is never rewritten — that is how you swap two characters safely.

Examples

print('abc'.translate(str.maketrans('abc', 'xyz')))  # → xyz
print('a-b-c'.translate(str.maketrans('', '', '-')))  # → abc
print('cat'.translate({ord('a'): 'A'}))  # → cAt

See also

Open in the full glossarydocs.python.orgReport an inaccuracy