Character Translation using Python (like the tr command)
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'