Eliminate a list of characters from a string?

Terry Reedy tjreedy at udel.edu
Thu Mar 27 14:25:39 EST 2003


"Max" <maxx at easynews.com> wrote in message
news:hoi68v81mabhrqgae0blpdpc04u2i15jhk at 4ax.com...
> What is the simplest method (that does not perform too poorly) for
eliminating
> any of a list of characters from a string. Currently, I ahev a
script that used
> multiple string.replace statements. In other words, if I have the
string
> 'A1B2C3' and want to eliminate the numbers leaving 'ABC' I could
use:
>
> S1='A1B2C3'
> S2=STRING.REPLACE(S1,'1','')
> S2=STRING.REPLACE(S2,'2','')
> S2=STRING.REPLACE(S2,'3','')
>
> However, if the list of eliminated characters is long, it seems a
bit
> inefficient.

>>> str.translate.__doc__
'S.translate(table [,deletechars]) -> string\n\nReturn a copy of the
string S, w
here all characters occurring\nin the optional argument deletechars
are removed,
 and the\nremaining characters have been mapped through the
given\ntranslation t
able, which must be a string of length 256.'
>>>
>>> id = ''.join(map(chr,range(256)))
>>> 'abc'.translate(id,'c')
'ab'

This would be most useful if it did not require a 'fake' no-effect
'identity table' to make use of the optional deletechars string, or if
such were an attribute of the str type.

Terry J. Reedy








More information about the Python-list mailing list