Replace Several Items

Gewton Jhames gjhames at gmail.com
Thu Aug 14 11:25:55 EDT 2008


thanks, guys.

On Thu, Aug 14, 2008 at 7:35 AM, M.-A. Lemburg <mal at egenix.com> wrote:

> 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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080814/f2d43381/attachment-0001.html>


More information about the Python-list mailing list