Content · Programming · Python

Python str.maketrans Method: Usage and Examples

str.maketrans() constructs a translation table for str.translate(). It accepts a mapping or pairs of equal-length strings, optionally with characters to delete. Learn with a clear example and common mistakes to avoid.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.maketrans Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.maketrans() constructs a translation table for str.translate(). It accepts a mapping or pairs of equal-length strings, optionally with characters to delete.

When You Would Use This


Replace dots and hyphens in simple internal reference labels.

Step-by-Step Example


translation_table = str.maketrans({"-": "_", ".": None})
original_reference = "AB-45.6"
print(original_reference.translate(translation_table))

How the Example Works


The hyphen becomes an underscore, and the dot is deleted. maketrans() prepares the table but does not transform any string until translate() is called.

Example Output


AB_456

Try It Yourself


Create a mapping that changes spaces to underscores and deletes exclamation points.

Common Beginner Mistakes


  • Expecting maketrans() to return the translated string.
  • Assuming all replacement values must be a single character.
  • Using character deletion as a substitute for validating meaningful identifiers.

Key Takeaways


  • str.maketrans() constructs a translation table for str.translate().
  • The hyphen becomes an underscore, and the dot is deleted.
  • Avoid this mistake: Expecting maketrans() to return the translated string.
Share this resourceSend this page to someone who may find it useful.