Better string.translate?

Alex Martelli aleaxit at
Thu Mar 15 10:13:06 CET 2001

"Stowasser Harald" <stowasser.h at> wrote in message
news:3ab0749f$1_3 at
> "Steve Purcell" <stephen_purcell at> schrieb :
> > Use the 'sub' function in the 're' module:
> Thank you, but i don't want do delete the characters. I need to
> translate them into Spaces.
> Anybody knows how?

This was Steve's suggestion for removal:

>> import re
>> re.sub('[^abcd]','', "string from which to remove all but a, b, c or d")

And this will change-into-space instead:

>> import re
>> re.sub('[^abcd]',' ', "string from which to remove all but a, b, c or d")
'               c            a   b   a  b  c    d'

See the difference?  It's all in the second parameter to re.sub --
*what* you want to change each matched-substring to.  Change it
to an empty-string, it's deleted from the result; change it to a
space, it's changed into a space.


More information about the Python-list mailing list