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 strngHere 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 trangBecome an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access