'string'.strip(chars)-like function that removes from the middle?

Maric Michaud maric at aristote.info
Mon Jun 16 19:07:28 CEST 2008


Le Monday 16 June 2008 18:58:06 Ethan Furman, vous avez écrit :
> The strip() method of strings works from both ends towards the middle.
> Is there a simple, built-in way to remove several characters from a
> string no matter their location? (besides .replace() ;)
>
> For example:
> .strip --> 'www.example.com'.strip('cmowz.')
> 'example'
> .??? --> --- 'www.example.com'.strip('cmowz.')
> 'exaple'

As Larry Bates said the python way is to use str.join, but I'd do it with a 
genexp for memory saving, and a set to get O(1) test of presence.

to_remove = set('chars')
''.join(e for in string_ if e not in to_remove)

Note that this one will hardly be defeated by other idioms in python (even 
regexp).

Using a genexp is free and a good practice, using a set, as it introduce one 
more step, can be considered as premature optimisation and the one liner :

''.join(e for in string_ if e not in 'chars')

may be preferred.

-- 
_____________

Maric Michaud



More information about the Python-list mailing list