The str.translate(table) method returns a copy of the string in which each character has been mapped through a translation table (typically constructed via str.maketrans()).
The Simultaneous 1-Pass Advantage: Unlike sequential str.replace() chaining where earlier substitutions can collide with later rules (e.g. attempting to swap 'A' and 'B'), translate() performs simultaneous, collision-free single-pass mapping. It is also Python's fastest native C mechanism for mass-deleting characters such as punctuation.
The translation pipeline pairs two complementary string methods:
str.translate(table, /)
str.maketrans(x[, y[, z]])
| Method / Component | Type | Role | Description |
|---|---|---|---|
str.translate(table) |
mapping |
Execution | Applies translation table mapping Unicode ordinals (integers) to replacement characters, strings, or None. |
str.maketrans() |
Static helper | Table Factory | Generates a valid Unicode translation dictionary from strings or dictionaries. |
dict mapping integer Unicode code points (ordinals) to replacement code points, string values, or None. For instance, mapping 'a' (97) to 'x' (120) produces {97: 120}. Mapping 'z' to None instructs Python to delete 'z'.
Python's str.maketrans() provides three flexible invocation signatures:
Accepts a dictionary where keys are single characters (or ordinals) and values are characters, strings, or None:
table = str.maketrans({"<": "<", ">": ">", "@": None})
text = "<user@host>"
print(text.translate(table)) # Output: '<userhost>'
Maps each character in string x to the corresponding character at the same index in string y:
table = str.maketrans("abc", "xyz")
print("abcdef".translate(table)) # Output: 'xyzdef'
ValueError: the first two maketrans arguments must have equal length.The third parameter, z, specifies an entire string of characters that will be mapped to None (deleted from the output):
# Map digits 1->A, 2->B, and delete all hyphens and spaces
table = str.maketrans("12", "AB", "- ")
sample = "1-2-1 2"
print(sample.translate(table)) # Output: 'ABAB'
Sequential str.replace() calls suffer from rule collision when swapping tokens. str.translate() evaluates all mappings simultaneously in a single pass:
source = "ABBA"
# FLAWED: replace() sequential chaining
broken = source.replace("A", "B").replace("B", "A")
print("Chained replace():", broken) # Produces 'AAAA' (Collided!)
# ROBUST: translate() simultaneous mapping
swap_table = str.maketrans("AB", "BA")
clean = source.translate(swap_table)
print("translate(): ", clean) # Produces 'BAAB' (Correct!)
Expected Output:
Chained replace(): AAAA
translate(): BAAB
Removing unwanted characters using str.translate() with the 3-argument str.maketrans('', '', delete_chars) is implemented directly in native C and runs orders of magnitude faster than loops or regex:
import string
raw_document = "Hello, world! Welcome to Python: fast, clean, & robust."
# Pass empty strings for x and y, and string.punctuation for deletion
strip_punct_table = str.maketrans("", "", string.punctuation)
cleaned = raw_document.translate(strip_punct_table)
print("Stripped punctuation:", cleaned)
Expected Output:
Stripped punctuation: Hello world Welcome to Python fast clean robust
Computing Watson-Crick reverse complements for DNA genomic sequences (A↔T, C↔G):
def dna_reverse_complement(sequence: str) -> str:
# 1. Translate complements simultaneously
comp_table = str.maketrans("ATCGatcg", "TAGCtagc")
complemented = sequence.translate(comp_table)
# 2. Reverse 5' to 3' direction
return complemented[::-1]
dna = "ATGCGATC"
print("Original DNA: ", dna)
print("Reverse Complement: ", dna_reverse_complement(dna))
Expected Output:
Original DNA: ATGCGATC
Reverse Complement: GATCGCAT
Implementing obfuscation ciphers with zero external dependencies:
import string
def rot13(text: str) -> str:
lower_in = string.ascii_lowercase
lower_out = lower_in[13:] + lower_in[:13]
upper_in = string.ascii_uppercase
upper_out = upper_in[13:] + upper_in[:13]
table = str.maketrans(lower_in + upper_in, lower_out + upper_out)
return text.translate(table)
secret = rot13("Python Tutorial on plus2net")
print("Encrypted: ", secret)
print("Decrypted: ", rot13(secret))
Expected Output:
Encrypted: Clguba Ghgbevny ba cyhf2arg
Decrypted: Python Tutorial on plus2net
Extracting only numeric digits from formatted telephone and identity strings:
def extract_digits_only(raw_string: str) -> str:
# Delete all non-digit characters in one C pass
non_digits = "".join(chr(i) for i in range(128) if not chr(i).isdigit())
table = str.maketrans("", "", non_digits)
return raw_string.translate(table)
phone = "+1 (800) 555-0199 ext. 42"
print("Extracted digits:", extract_digits_only(phone))
Expected Output:
Extracted digits: 1800555019942
str.translate() operates on individual characters. You cannot map multi-character words like "cat" → "dog" using str.maketrans("cat", "dog") because that maps c→d, a→o, and t→g! For multi-character word substitutions, use str.replace() or regular expressions.
If the first two arguments to maketrans() have different lengths, Python immediately raises an exception:
# ValueError: the first two maketrans arguments must have equal length
str.maketrans("abc", "xy")
Below is a production-grade utility class, CharacterTranslator, demonstrating DNA reverse complements, punctuation removal, and automated unit assertions:
import string
class CharacterTranslator:
@staticmethod
def swap_tokens(text: str, set_a: str, set_b: str) -> str:
"""Simultaneously swaps characters in set_a with set_b."""
table = str.maketrans(set_a + set_b, set_b + set_a)
return text.translate(table)
@staticmethod
def strip_punctuation(text: str) -> str:
"""Removes all standard ASCII punctuation in a single C pass."""
table = str.maketrans("", "", string.punctuation)
return text.translate(table)
@staticmethod
def dna_complement(dna_seq: str) -> str:
"""Calculates reverse complement of DNA sequence."""
table = str.maketrans("ATCG", "TAGC")
return dna_seq.upper().translate(table)[::-1]
# ==========================================
# SELF-CHECKING UNIT ASSERTIONS
# ==========================================
translator = CharacterTranslator()
# 1. Simultaneous swapping without collision
assert translator.swap_tokens("ABBA", "A", "B") == "BAAB"
assert translator.swap_tokens("XYZ", "X", "Z") == "ZYX"
# 2. Fast punctuation deletion
raw = "Hello, world! How are you?"
assert translator.strip_punctuation(raw) == "Hello world How are you"
# 3. DNA reverse complement
assert translator.dna_complement("ATGCGATC") == "GATCGCAT"
assert translator.dna_complement("AAAA") == "TTTT"
# 4. 1-arg dictionary form with multi-char replacement value
html_table = str.maketrans({"<": "<", ">": ">"})
assert "<div>".translate(html_table) == "<div>"
# 5. ValueError validation on unequal length strings
try:
str.maketrans("abc", "xy")
assert False, "Expected ValueError not raised"
except ValueError as e:
assert "equal length" in str(e)
print("Swapped tokens: ", translator.swap_tokens("CAT_AND_DOG", "C", "D"))
print("Punctuation stripped:", translator.strip_punctuation("Price: $12.99!"))
print("DNA complement: ", translator.dna_complement("CCGGTA"))
print("All str.translate() unit assertions passed successfully!")
Open in Google Colab View on GitHub
Run all character translation examples interactively, contrast translate() with replace(), build DNA reverse complement engines, and implement ROT13 ciphers in Google Colab.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.