Replace Several Items

M.-A. Lemburg mal at egenix.com
Thu Aug 14 12:35:24 CEST 2008


On 2008-08-13 23:54, John Krukoff wrote:
> On Wed, 2008-08-13 at 09:39 -0700, gjhames wrote:
>> I wish to replace several characters in my string to only one.
>> Example, "-", "." and "/" to nothing ""
>> I did like that:
>> my_string = my_string.replace("-", "").replace(".", "").replace("/",
>> "").replace(")", "").replace("(", "")
>>
>> But I think it's a ugly way.
>>
>> What's the better way to do it?
>> --
>> http://mail.python.org/mailman/listinfo/python-list
> 
> 
> The maketrans interface is a bit clunky, but this is what
> string.translate is best at:
> 
> >>> import string
>>>> '-./other'.translate( string.maketrans( '', '' ), '-./' )
> 'other'
> 
> It'd be interesting to see where it falls in the benchmarks, though.
> 
> It's worth noting that the interface for translate is quite different
> for unicode strings.

Right. Unicode .translate() uses a dictionary for defining the
mapping.

Another approach is to use the re module:

 >>> import re
 >>> re.sub('[-./()]', '', '-./other')
'other'

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Aug 14 2008)
 >>> Python/Zope Consulting and Support ...        http://www.egenix.com/
 >>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
 >>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

:::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ::::


    eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
     D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
            Registered at Amtsgericht Duesseldorf: HRB 46611



More information about the Python-list mailing list