
May 7th, 2004, 01:37 PM
|
|
Contributing User
|
|
Join Date: Feb 2004
Location: London, England
|
|
If you only want to remove all instances of a single character, then you can use the string replace method:
Code:
>>> txt = 'hello world'
>>> txt.replace('l', '')
'heo word'
To remove a set of characters then you could use the filter function:
Code:
>>> filter(lambda x: x not in 'aeiou', txt)
'hll wrld'
Alternatively you could use the string module's translate and maketrans functions:
Code:
>>> import string
>>> trans = string.maketrans('', '')
>>> string.translate(txt, trans, 'aeiou')
'hll wrld'
The translate function is more useful if you wish to replace some characters and remove others.
EDIT: translate is also much faster than filter, since it is implemented entirely in C, while filter will need to call a python function for each character. This probably does not matter much for scripts occasionally acting on short strings, but can be critical if performance is an issue.
Dave - The Developers' Coach
Last edited by DevCoach : May 8th, 2004 at 05:04 PM.
|