Wednesday, December 13, 2017

translation method in string at codelent


Similar to replace, translate replaces parts of a string, but unlike replace, translate works
only with single characters. Its strength lies in that it can perform several replacements simultaneously,
and can do so more efficiently than replace.
There are quite a few rather technical uses for this method (such as translating newline
characters or other platform-dependent special characters), but let’s consider a simpler
(although slightly more silly) example. Let’s say you want to translate a plain English text into
one with a German accent. To do this, you must replace the character c with k, and s with z.

Before you can use translate, however, you must make a translation table. This translation
table is a full listing of which characters should be replaced by which. Because this table
(which is actually just a string) has 256 entries, you won’t write it out yourself. Instead, you’ll
use the function maketrans from the string module.
The maketrans function takes two arguments: two strings of equal length, indicating that
each character in the first string should be replaced by the character in the same position in the
second string. Got that? In the case of our simple example, the code would look like the
following:
>>> from string import maketrans
>>> table = maketrans('cs', 'kz')

WHAT’S IN A TRANSLATION TABLE?
A translation table is a string containing one replacement letter for each of the 256 characters in the ASCII
character set:
>>> table = maketrans('cs', 'kz')
>>> len(table)
256
>>> table[97:123]
'abkdefghijklmnopqrztuvwxyz'
>>> maketrans('', '')[97:123]
'abcdefghijklmnopqrstuvwxyz'
As you can see, I’ve sliced out the part of the table that corresponds to the lowercase letters. Take a look
at the alphabet in the table and that in the empty translation (which doesn’t change anything). The empty
translation has a normal alphabet, while in the preceding code, the letter c has been replaced by k, and s has
been replaced by z.
Once you have this table, you can use it as an argument to the translate method, thereby
translating your string:
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
An optional second argument can be supplied to translate, specifying letters that should
be deleted. If you wanted to emulate a really fast-talking German, for instance, you could
delete all the spaces:
>>> 'this is an incredible test'.translate(table, ' ')
'thizizaninkredibletezt'
See also: replace, lower.

Function Description
string.capwords(s[, sep]) Splits s with split (using sep), capitalize items, and join with a
single space
string.maketrans(from, to) Makes a translation table for translate

0 comments:

Post a Comment