Better string.translate?

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


"Stowasser Harald" <stowasser.h at idowa.de> wrote in message
news:3ab0749f$1_3 at news.zet.net...
> "Steve Purcell" <stephen_purcell at yahoo.com> 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")
'cababcd'


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.


Alex








More information about the Python-list mailing list