04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

64 CHAPTER 3 ■ WORKING WITH STRINGS<br />

translate<br />

Similar to replace, translate replaces parts of a string, but unlike replace, translate only works<br />

with single characters. Its strength lies in that it can perform several replacements simultaneously,<br />

and can do so more efficiently than replace.<br />

There are quite a few rather technical uses for this method (such as translating newline<br />

characters or other platform-dependent special characters), but let’s consider a simpler<br />

(although slightly more silly) example. Let’s say you want to translate a plain English text into<br />

one with a German accent. To do this, you must replace the character “c” with “k,” and “s” with “z.”<br />

Before you can use translate, however, you must make a translation table. This translation<br />

table is a full listing of which characters should be replaced by which. Because this table (which is<br />

actually just a string) has 256 entries, you won’t write it out yourself: You’ll use the function<br />

maketrans from the string module.<br />

The maketrans function takes two arguments: two strings of equal length, indicating that<br />

each character in the first string should be replaced by the character in the same position in the<br />

second string. Got that? In the case of our simple example, the code would look like the following:<br />

>>> from string import maketrans<br />

>>> table = maketrans('cs', 'kz')<br />

WHAT’S IN A TRANSLATION TABLE?<br />

A translation table is a string containing one replacement letter for each of the 256 characters in the ASCII<br />

character set:<br />

>>> table = maketrans('cs', 'kz')<br />

>>> len(table)<br />

256<br />

>>> table[97:123]<br />

'abkdefghijklmnopqrztuvwxyz'<br />

>>> maketrans('', '')[97:123]<br />

'abcdefghijklmnopqrstuvwxyz'<br />

As you can see, I’ve sliced out the part of the table that corresponds to the lowercase letters. Take a look<br />

at the alphabet in the table and that in the empty translation (which doesn’t change anything). The empty<br />

translation has a normal alphabet, while in the preceding code, the letter “c” has been replaced by “k,” and<br />

“s” has been replaced by “z.”<br />

Once you have this table, you can use it as an argument to the translate method, thereby<br />

translating your string:<br />

>>> 'this is an incredible test'.translate(table)<br />

'thiz iz an inkredible tezt'

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!