Replace Several Items
John Krukoff
jkrukoff at ltgc.com
Wed Aug 13 17:54:15 EDT 2008
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.
--
John Krukoff <jkrukoff at ltgc.com>
Land Title Guarantee Company
More information about the Python-list
mailing list