Python Glossary Русский

Python 3.0+Strings (str)function

str.maketrans

replacement

Static method: build a translation table for translate from two strings (plus optional deletes).

Syntax

str.maketrans(x[, y[, z]])

The table maps character by character: translate cannot swap a multi-character substring — that is str.replace's job. The two-string form requires both strings to be the same length, otherwise ValueError, and the optional third argument lists characters to drop. The dict form is more flexible: keys are single characters or their code points, values may be strings of any length or None, which means delete.

Examples

print('abc'.translate(str.maketrans('ab', 'AB')))  # → ABc
t = str.maketrans({'x': 'y'}); print('xox'.translate(t))  # → yoy
print('a1b2'.translate(str.maketrans('', '', '12')))  # → ab

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy