Character Translation using Python (like the tr command)

Viewed 35945

Is there a way to do character translation / transliteration (kind of like the tr command) using Python?

Some examples in Perl would be:

my $string = "some fields";
$string =~ tr/dies/eaid/;
print $string;  # domi failed

$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "$string\n";  # b b   b.  (because option "d" is used to delete characters not replaced)
6 Answers

See string.translate

import string
"abc".translate(string.maketrans("abc", "def")) # => "def"

Note the doc's comments about subtleties in the translation of unicode strings.

And for Python 3, you can use directly:

str.translate(str.maketrans("abc", "def"))

Edit: Since tr is a bit more advanced, also consider using re.sub.

We build a map and then translate letter by letter. When using get for dictionary then the second argument specifying what to return if not find anything.

It could be easily transferred to separate function. Mostly should be very efficient.

def transy(strin, old, new):
  assert len(old)==len(new)
  trans = dict(zip(list(old),list(new)))
  res =  "".join([trans.get(i,i) for i in strin])
  return res

>>> transy("abcd", "abc", "xyz")
'xyzd'
Related