By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,603 Members | 1,051 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,603 IT Pros & Developers. It's quick & easy.

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

P: n/a
Greetings.

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'
--
Ethan

Jun 27 '08 #1
Share this Question
Share on Google+
4 Replies

P: n/a
Ethan Furman wrote:
Greetings.

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'
--
Ethan
filter()
>>removeChars = ';j'
filter(lambda c: c not in removeChars, x)
'asdfklasdfkl'
>>>
or

a list comprehension

x="asdfjkl;asdfjkl;"
>>''.join([c for c in x if c not in ';'])
'asdfjklasdfjkl'

-Larry
Jun 27 '08 #2

P: n/a
Ethan Furman wrote:
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() ;)
>>identity = "".join(map(chr, range(256)))
'www.example.com'.translate(identity, 'cmowz.')
'exaple'

Peter
Jun 27 '08 #3

P: n/a
On Jun 16, 10:09*am, Peter Otten <__pete...@web.dewrote:
Ethan Furman wrote:
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() ;)
>identity = "".join(map(chr, range(256)))
'www.example.com'.translate(identity, 'cmowz.')

'exaple'
And in Py2.6, you'll be able to simplify further:
>>'abcde'.translate(None, 'bd')
'ace'
Raymond
Jun 27 '08 #4

P: n/a
Peter Otten schreef:
Ethan Furman wrote:
>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() ;)
>>>identity = "".join(map(chr, range(256)))
Or

identity = string.maketrans('', '')
>>>'www.example.com'.translate(identity, 'cmowz.')
'exaple'

--
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
-- Isaac Asimov

Roel Schroeven
Jun 27 '08 #5

This discussion thread is closed

Replies have been disabled for this discussion.