Translate Python string with translate function
Translate string
The translate
method is like the replace
method, which replace occurrence of a string
with another string. But unlike replace
method the translate method only works on
one char at one time and can do the replacement
simultaneously. translate method has the following
syntax.
s.translate(table [, deletechars])
Deletes all characters from string s that are in deletechars (if present), then translates the characters using table, a 256-character string giving the translation for each character value indexed by its ordinal.
from string import maketrans
# w w w . j ava2s . c o m
table = maketrans('a', 'z')
len(table)
print table[97:123]
print maketrans('', '')[97:123]
The code above generates the following result.
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. The empty translation has a normal alphabet, while in the preceding code, the letter "a" 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:
from string import maketrans
table = maketrans('a', 'z')
print 'this is a test'.translate(table)
An optional second argument can be supplied to translate, specifying letters that should be deleted. To delete all the spaces:
from string import maketrans
table = maketrans('a', 'z')
'this is an incredible test'.translate(table, ' ')