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)
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.
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.
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
.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With