Deleting characters from a string

Tim Peters tim_one at email.msn.com
Sat Jun 5 12:56:44 EDT 1999


[Hrvoje Niksic]
> string.translate can delete characters from a string, as well as
> translate them.  But what if I want *only* to delete them?  Currently
> I do this:
>
> dummytable = string.maketrans('', '')
>
> ...
>   host = string.translate(host, dummytable, ' "')
> ...
>
> What I would really like to be able to do is write:
>
>   host = string.translate(host, None, ' "')

That's easy; change your assignment to

None = string.maketrans('', '')

and you can write exactly that <wink>.

It's (yours, not mine ...) a decent idea; in the meantime how about writing
a little wrapper

def deletechars(s, todelete, id=string.maketrans('', '')):
    return string.translate(s, id, todelete)

Then you can use an interface that doesn't bother you with arguments you
don't care about.  Or you can borrow the string module's private spelling,

    host = string.translate(host, string._idmap, ' "')

Maybe good too if _idmap lost its leading underscore -- it's been in the
module forever, and is exactly the "don't translate anything" argument you
need.

tweakingly y'rs  - tim






More information about the Python-list mailing list