Replace Several Items
gminick at nie.ma.takiego.adresu.w.sieci.pl
Thu Aug 14 00:15:49 CEST 2008
Dnia Wed, 13 Aug 2008 23:31:42 +0200, Fredrik Lundh napisa³(a):
>>> 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?
>> The regular expression is probably the best way to do it,
>> but if you really want to use replace, you can also use
>> the replace method in loop:
> suggested exercise: benchmark re.sub with literal replacement, re.sub
> with callback (lambda m: ""), repeated replace, and repeated use of the form
> if ch in my_string:
> my_string = my_string.replace(ch, "")
> on representative data.
I don't have to, I can anticipate the results. I mentioned above
that using re is the best approach, but if one really wants to use
replace() multiple times (which will be slow, of course), it can
be done a bit cleaner than with str.replace().replace().replace()...
More information about the Python-list