tags:

views:

467

answers:

2

Is there a way to do character translation (kind of like the tr command) using python

+6  A: 

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.

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

Richard Levasseur
+2  A: 

if your are 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 python2.x use additional argument to translate function:

>>> "abc".translate(None, 'b')
'ac'
Piotr Czapla