ZetCode

Python translate and maketrans

last modified November 19, 2026 Python 3.15

In this article we show how to map and delete characters with the translate method in Python.

The str.translate method goes through a string character by character and looks up each character in a translation table. The table decides whether the character is kept, replaced, or deleted. The static method str.maketrans builds such tables. Because each character is looked up once, translate performs many single-character replacements in one pass. A short introduction is part of Python replace string; this article covers the method in depth.

The translate method

With two strings of equal length, maketrans maps each character of the first string to the character at the same position in the second.

translate_basic.py
#!/usr/bin/python

text = 'a quiet afternoon at the lake'

table = str.maketrans('aeiou', 'AEIOU')
print(text.translate(table))

leet = str.maketrans('aeiost', '431057')
print(text.translate(leet))

The first table uppercases the vowels. The second replaces letters with similar-looking digits. Characters missing from the table, such as consonants and spaces, are copied unchanged.

$ python translate_basic.py
A qUIEt AftErnOOn At thE lAkE
4 qu137 4f73rn00n 47 7h3 l4k3

The translation table

A translation table is a dictionary that maps Unicode code points, which are integers, to replacement strings, code points, or None.

table.py
#!/usr/bin/python

table = str.maketrans('ab', 'xy')
print(table)

table = {ord('a'): 'x', ord('b'): 'y'}
print('abba cab'.translate(table))

print(str.maketrans({'a': 'x', 'b': None}))

The table from maketrans maps the code point of a, 97, to that of x, 120. We can write such a dictionary ourselves with ord. Given a single dictionary, maketrans converts its keys from characters to code points, so we do not have to call ord.

$ python table.py
{97: 120, 98: 121}
xyyx cxy
{97: 'x', 98: None}

Deleting characters

The third argument of maketrans lists characters to delete. They are mapped to None.

delete_chars.py
#!/usr/bin/python

import string

text = 'Hello, World! Is it (really) 2026?'

no_punct = str.maketrans('', '', string.punctuation)
print(text.translate(no_punct))

no_digits = str.maketrans('', '', string.digits)
print(text.translate(no_digits))

phone = '+421 (2) 555-0142'
print(phone.translate(str.maketrans('', '', ' ()-')))

The string.punctuation constant contains the ASCII punctuation characters, and string.digits the digits 0 to 9. The first two arguments are empty strings, because we do not map anything. The last line reduces a phone number to the plus sign and digits.

$ python delete_chars.py
Hello World Is it really 2026
Hello, World! Is it (really) ?
+42125550142

Mapping to several characters

In a dictionary table, a character can be replaced with a string of any length.

transliterate.py
#!/usr/bin/python

GERMAN = str.maketrans({'ä': 'ae', 'ö': 'oe', 'ü': 'ue', 'ß': 'ss',
                        'Ä': 'Ae', 'Ö': 'Oe', 'Ü': 'Ue'})

for word in ['Müller', 'Straße', 'Ölgemälde', 'Äpfel']:
    print(word, word.translate(GERMAN))

German umlauts are written as two letters when only ASCII is available, and ß becomes ss. The two-string form of maketrans cannot do this, because it maps one character to one character.

$ python transliterate.py
Müller Mueller
Straße Strasse
Ölgemälde Oelgemaelde
Äpfel Aepfel

Simultaneous replacement

Chained replace calls work one after another, and a later call can undo an earlier one. The translate method looks up each character of the original string only once.

swap.py
#!/usr/bin/python

text = 'wait for the train'

print(text.replace('t', 'w').replace('w', 't'))

print(text.translate(str.maketrans('tw', 'wt')))

number = '1,234,567.89'
print(number.translate(str.maketrans(',.', '.,')))

We want to swap the letters t and w. The first replace turns every t into w, and the second turns all of them, old and new, into t. The translate version swaps the letters correctly. The same problem arises when converting a number from the English to the German format, where commas and dots swap their roles.

$ python swap.py
tait for the train
taiw for whe wrain
1.234.567,89

Caesar cipher

The Caesar cipher replaces each letter with the letter a fixed number of positions further in the alphabet. A rotated alphabet in maketrans makes this a one-line operation.

caesar.py
#!/usr/bin/python

from string import ascii_lowercase as lower, ascii_uppercase as upper


def caesar(shift):
    shift %= 26
    return str.maketrans(lower + upper,
                         lower[shift:] + lower[:shift] +
                         upper[shift:] + upper[:shift])


message = 'Meet me at the Old Bridge, 10 PM.'

secret = message.translate(caesar(3))
print(secret)
print(secret.translate(caesar(-3)))
print(message.translate(caesar(13)).translate(caesar(13)))

The caesar function maps the alphabet to the same alphabet rotated by shift letters, using slices; uppercase letters get their own rotation. A negative shift decodes the message, because the modulo turns it into a shift forward. A shift of 13, known as ROT13, is its own inverse. Digits and punctuation are not changed. The cipher is a classic exercise, not a way to protect data.

$ python caesar.py
Phhw ph dw wkh Rog Eulgjh, 10 SP.
Meet me at the Old Bridge, 10 PM.
Meet me at the Old Bridge, 10 PM.

DNA complement

In molecular biology, the two strands of DNA pair the bases A with T and C with G. The complement of a sequence is a straightforward translation.

dna.py
#!/usr/bin/python

COMPLEMENT = str.maketrans('ACGTacgt', 'TGCAtgca')


def reverse_complement(seq):
    return seq.translate(COMPLEMENT)[::-1]


seq = 'ATGCGTTAgcc'
print(seq.translate(COMPLEMENT))
print(reverse_complement(seq))
print(reverse_complement(reverse_complement(seq)) == seq)

The table pairs the bases in both directions and in both cases; lowercase letters often mark regions of lower quality. The reverse complement reads the other strand in its natural direction, so we reverse the translated string with the [::-1] slice. Applying it twice gives the original sequence.

$ python dna.py
TACGCAATcgg
ggcTAACGCAT
True

Custom tables

The table does not have to be a dictionary. The method calls the __getitem__ method of the table with the code point; raising LookupError keeps the character unchanged.

custom_table.py
#!/usr/bin/python

class AsciiOnly:

    def __getitem__(self, code):
        if code < 128:
            raise LookupError
        return '?'


class Transliterator(dict):

    def __init__(self, mapping):
        super().__init__(str.maketrans(mapping))
        self.unknown = set()

    def __missing__(self, code):
        if code >= 128:
            self.unknown.add(chr(code))
        raise LookupError


text = 'Žltý kôň 🐎 skáče'
print(text.translate(AsciiOnly()))

slovak = Transliterator({'Ž': 'Z', 'ý': 'y', 'ô': 'o', 'ň': 'n'})
print(text.translate(slovak))
print(sorted(slovak.unknown))

The AsciiOnly table keeps ASCII characters and replaces all others with a question mark, without listing them. The Transliterator class is a dictionary subclass; its __missing__ method is called for characters that are not in the dictionary. It records the non-ASCII ones and keeps them, so after the translation we know which characters still need a mapping.

$ python custom_table.py
?lt? k?? ? sk??e
Zlty kon 🐎 skáče
['á', 'č', '🐎']

Translating bytes

The bytes type has translate and maketrans too. The table is a bytes object of 256 bytes, and characters to delete are passed as a separate argument.

bytes_translate.py
#!/usr/bin/python

data = b'Hello\r\nWorld\x00\x07!\r\n'

table = bytes.maketrans(b'\r', b'\n')
print(data.translate(table))

printable = bytes(range(32, 127)) + b'\n'
junk = bytes(set(range(256)) - set(printable))
print(data.translate(None, junk))

upper = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz',
                        b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
print(b'falcon 42'.translate(upper))

The first table turns carriage returns into newlines. Passing None as the table and a set of bytes as the second argument only deletes bytes; here we remove all bytes except printable ASCII and the newline. The last table uppercases ASCII letters.

$ python bytes_translate.py
b'Hello\n\nWorld\x00\x07!\n\n'
b'Hello\nWorld!\n'
b'FALCON 42'

Performance

We compare three ways of removing punctuation from a long text: chained replace calls, translate, and a regular expression.

timing.py
#!/usr/bin/python

import re
import string
import timeit

text = 'Hello, World! How are you? (Fine; thanks.) ' * 1000

table = str.maketrans('', '', string.punctuation)
pattern = re.compile(f'[{re.escape(string.punctuation)}]')


def by_replace(s):
    for c in string.punctuation:
        s = s.replace(c, '')
    return s


def by_translate(s):
    return s.translate(table)


def by_regex(s):
    return pattern.sub('', s)


assert by_replace(text) == by_translate(text) == by_regex(text)

for fn in (by_replace, by_translate, by_regex):
    t = timeit.timeit(lambda: fn(text), number=200)
    print(f'{fn.__name__:13} {t * 1000:7.1f} ms')

The assert statement checks that all three functions give the same result. The chained replace calls scan the text once for each of the 32 punctuation characters, while translate scans it once. The regular expression also scans the text once, but it has more work to do for each character. The exact times depend on the computer.

$ python timing.py
by_replace       95.3 ms
by_translate      8.5 ms
by_regex        131.9 ms

Safe file names

In the last example we turn document titles into file names that are valid on Windows, macOS, and Linux.

safe_filename.py
#!/usr/bin/python

import unicodedata

FORBIDDEN = '<>:"/\\|?*'
CONTROL = ''.join(map(chr, range(32)))
TABLE = str.maketrans({**dict.fromkeys(FORBIDDEN, '_'),
                       **dict.fromkeys(CONTROL),
                       ' ': '-'})


def safe_filename(name, ascii_only=False):
    name = unicodedata.normalize('NFC', name).translate(TABLE)
    if ascii_only:
        decomposed = unicodedata.normalize('NFKD', name)
        name = decomposed.encode('ascii', 'ignore').decode()
    return name.strip('.-') or 'unnamed'


titles = ['Report: Q3/2026 *final*', 'Čerešne a jahody.txt',
          'tab\there', '...', 'a<b>c?.pdf']

for title in titles:
    print(f'{title!r:28} {safe_filename(title):24} '
          f'{safe_filename(title, ascii_only=True)}')

One table does three jobs: it replaces the characters forbidden in Windows file names with an underscore, deletes control characters, and turns spaces into hyphens. The dict.fromkeys calls build the parts of the mapping, and the dictionary unpacking merges them. With ascii_only, the NFKD normalization splits accented letters into a base letter and a combining mark, and encoding to ASCII with 'ignore' drops the marks. Leading and trailing dots and hyphens are stripped, and a name that ends up empty is replaced.

$ python safe_filename.py
'Report: Q3/2026 *final*'    Report_-Q3_2026-_final_  Report_-Q3_2026-_final_
'Čerešne a jahody.txt'       Čerešne-a-jahody.txt     Ceresne-a-jahody.txt
'tab\there'                  tabhere                  tabhere
'...'                        unnamed                  unnamed
'a<b>c?.pdf'                 a_b_c_.pdf               a_b_c_.pdf

Source

str.translate – Python documentation

str.maketrans – Python documentation

In this article we have mapped and deleted characters with translate and maketrans in Python. See also Python replace string, Python strip string, Python string case, and Python compare strings.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.