Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character Translation using Python (like the tr command)

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) 
like image 406
hhafez Avatar asked Feb 17 '09 06:02

hhafez


People also ask

What is TR () in Python?

This module is a Python implementation of the tr algorithm. tr(string1, string2, source, option='') If not given option, then replace all characters in string1 with the character in the same position in string2.

What is character translation in Python?

The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table. Use the maketrans() method to create a mapping table. If a character is not specified in the dictionary/table, the character will not be replaced.


2 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.

like image 71
Richard Levasseur Avatar answered Oct 18 '22 01:10

Richard Levasseur


If you're using python3 translate is less verbose:

>>> 'abc'.translate(str.maketrans('ac','xy')) 'xby' 

Ahh.. and there is also equivalent to tr -d:

>>> "abc".translate(str.maketrans('','','b')) 'ac'  

For tr -d with python2.x use an additional argument to translate function:

>>> "abc".translate(None, 'b') 'ac' 
like image 34
Piotr Czapla Avatar answered Oct 18 '22 02:10

Piotr Czapla