Name

maketrans

Synopsis

maketrans(from,onto)

Returns a translation table, which is a plain string of length 256 that provides a mapping from characters in ascending ASCII order to another set of characters. from and onto must be plain strings, with len( from ) equal to len( onto ). Each character in string from is mapped to the character at the corresponding position in string onto. For each character not listed in from, the translation table maps the character to itself. To get an identity table that maps each character to itself, call maketrans('','').

With the translate string method, you can delete characters as well as translate them. When you use translate just to delete characters, the first argument you pass to translate should be the identity table. Here’s an example of using the maketrans function and the string method translate to delete vowels:

import string
identity = string.maketrans('','')
print 'some string'.translate(identity,'aeiou')    # prints: sm strng

Here are examples of turning all other vowels into a’s and also deleting s’s:

intoas = string.maketrans('eiou','aaaa')
print 'some string'.translate(intoas)              # prints: sama strang
print 'some string'.translate(intoas,'s')          # prints: ama trang

Get Python in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.